请求与响应 .urlopen()
urllib.request.Request() 类型实例
import urllib.request #申请一个请求
import utllib.parse #格式化字符串
url = 'http://httpbin.org/get'
req = urllib.request.Request(url)
rsp = urllib.request.urlopen(req)
rsp.status #请求状态
.add_header(key,value) 添加头部信息
import urllib.error
import urllib.request
import urllib.parse
url = 'http://httpbin.org/get'
req = urllib.request.Request(url, method='GET')
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36')
rsq = urllib.request.urlopen(req)
b = rsq.read()
from pprint import pprint
pprint(b.decode())
('{\n'
' "args": {}, \n'
' "headers": {\n'
' "Accept-Encoding": "identity", \n'
' "Connection": "close", \n'
' "Host": "httpbin.org", \n'
' "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"\n'
' }, \n'
' "origin": "175.167.138.151", \n'
' "url": "http://httpbin.org/get"\n'
'}\n')
.Request(url,data='数据') 构造POST访问
import urllib.request
import urllib.parse
url = 'http://httpbin.org/post'
form = {'name':'Jin', 'age':20}
data = urllib.parse.urlencode(form)
data = data.encode()
req = urllib.request.Request(url, data=data)
rsq = urllib.request.urlopen(req)
b = rsq.read()
b = b.decode()
from pprint import pprint
pprint(b)
('{\n'
' "args": {}, \n'
' "data": "", \n'
' "files": {}, \n'
' "form": {\n'
' "age": "20", \n'
' "name": "Jin"\n'
' }, \n'
' "headers": {\n'
' "Accept-Encoding": "identity", \n'
' "Connection": "close", \n'
' "Content-Length": "15", \n'
' "Content-Type": "application/x-www-form-urlencoded", \n'
' "Host": "httpbin.org", \n'
' "User-Agent": "Python-urllib/3.6"\n'
' }, \n'
' "json": null, \n'
' "origin": "175.167.138.151", \n'
' "url": "http://httpbin.org/post"\n'
'}\n')
结果 http.client.HTTPResponse
- .status 状态码
- .getcode() 获取状态码
- .reason 状态文本
- .geturl() 获取URL
- .info() 获取元信息
- .read() 读取正文到字节
传参
data = {'name':'xxx', 'age':'xx'}
params = urllib.parse.urlencode(data)
rsp = urllib.request.urlopen(f'{url}?{params}')
b = rsp.read()
s = b.decode()
from pprint import pprint
pprint(s)