import urllib.request
request = urllib.request.Request('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
依然用urlopen()方法发送请求,参数不再是URl而是request对象。request对象构造:
class urllib.request.Request(url,data=None,headers={},origin_req_host=None,unverifiable=False,method=None)
url用于请求URL,比传参数;data如果要传,必须传bytes(字节流)类型。如果是字典,先用urllib.parse模块的urlencode()编码;headers是一个字典,请求头,可以通过调用请求实例的add_header()方法添加;origin_req_host指的是请求方的host名称或者IP地址;unverifiable表示这个请求是否是无法验证的,默认false,当为true时意思是用户没有足够的权限来选择接收这个请求结果;method表示请求使用的方法,比如get、post、put等。
import urllib.request
import urllib.parse
url= 'http://httpbin.org/post'
headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',
'Host':
'httpbin.org'
}
dict={
'name':'song'
}
data = bytes(urllib.parse.urlencode(dict),encoding='utf-8')
request = urllib.request.Request(url,data=data,headers=headers,method='POST')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
运行结果:
{
"args": {},
"data": "",
"files": {},
"form": {
"name": "song"
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "9",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-5f959329-58c3d928533881997a7de4bb"
},
"json": null,
"origin": "58.199.177.47",
"url": "http://httpbin.org/post"
}
另外headers也可以用add_header()来添加:
request = urllib.request.Request(url,data=data,headers=headers,method='POST')
request.add_header('Accept-Language','zh-CN,zh;q=0.9')