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))

你可能感兴趣的:(爬虫)