天天看點

urllib中的urlopen發送get和post請求

get請求

from urllib import request

url = 'http://www.baidu.com'

res = request.urlopen(url=url)
# print(res.read())
with open('baidu_index.html','w',encoding='utf-8') as f:
    f.write(res.read().decode('utf-8'))
           

post請求

import json
from urllib import request
from urllib import parse

url = 'https://fanyi.baidu.com/sug'

data_dic = {
    'kw':'girl'
}

data_parse = parse.urlencode(data_dic)
data_b = data_parse.encode('utf-8')
res = request.urlopen(url=url,data=data_b)
res_str = res.read().decode('utf-8')
print(json.loads(res_str))