官方文档:urllib3 2.0.4 documentation
pip install urllib3
urllib3
模块PoolManager
实例request()
方法import urllib3
def test_HTTP():
# 创建连接池对象,默认会校验证书
pm = urllib3.PoolManager()
# 发送HTTP请求
res = pm.request(method='GET', url="http://httpbin.org/robots.txt")
print(type(res))
import urllib3
def test_response():
# 创建连接池对象
pm = urllib3.PoolManager()
# 发送请求
resp = pm.request(method='GET', url="http://httpbin.org/ip")
print(resp.status) # 查看响应状态状态码
print(resp.headers) # 查看响应头信息
print(resp.data) # 查看响应原始二进制信息
import urllib3
import json
def test_response():
pm = urllib3.PoolManager()
resp = pm.request(method='GET', url="http://httpbin.org/ip")
# 获取二进制形式的响应内容
raw = resp.data
print(type(raw), raw)
# 使用utf-8解码成字符串
content = raw.decode('utf-8')
print(type(content), content)
# 将JSON字符串解析成字典对象
dict_obj = json.loads(content)
print(type(dict_obj), dict_obj)
print(dict_obj['origin'])
request(method, url, fields, headers, **)
method
:请求方式url
:请求地址headers
:请求头信息fields
:请求体数据body
:指定请求体类型tiemout
:设置超时时间headers
参数import urllib3
import json
def test_headers():
pm = urllib3.PoolManager()
url = "http://httpbin.org/get"
# 定制请求头
headers = {'School': 'hogwarts'}
resp = pm.request('GET', url, headers=headers)
fields
参数:适用于GET, HEAD, DELETE
请求url
:适用于POST, PUT
请求import urllib3
import json
# GET/HEAD/DELETE 请求
def test_fields():
pm = urllib3.PoolManager()
url = "http://httpbin.org/get"
fields = {'school': 'hogwarts'}
resp = pm.request(method='GET', url=url, fields=fields)
# POST/PUT 请求
def test_urlencode():
# 从内置库urllib的parse模块导入编码方法
from urllib.parse import urlencode
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
# POST和PUT请求需要编码后拼接到URL中
encoded_str = urlencode({'school': 'hogwarts'})
resp = pm.request('POST', url=url+"?"+encoded_str)
'Content-Type': 'multipart/form-data
import urllib3
import json
# POST/PUT 请求
def test_form():
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
fields = {'school': 'hogwarts'}
# fields数据会自动转成form格式提交
resp = pm.request('POST', url, fields=fields)
'Content-Type': 'application/json'
import urllib3
import json
def test_json():
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
# 设定请求体数据类型
headers={'Content-Type': 'application/json'}
# JSON文本数据
json_str = json.dumps({'school': 'hogwarts'})
resp = pm.request('POST', url, headers=headers, body=json_str)
timeout
:设置超时时间import urllib3
def test_timeout():
pm = urllib3.PoolManager()
# 访问这个地址,服务器会在3秒后响应
url = "http://httpbin.org/delay/3"
# 设置超时时长
resp = pm.request(method='GET', url=url, timeout=4.0)
assert resp.status == 200
cert_reqs
参数"CERT_REQUIRED"
:需要校验"CERT_NONE"
:取消校验import urllib3
import json
def test_HTTPS():
# 创建不校验证书的连接池对象
pm_https = urllib3.PoolManager(cert_reqs="CERT_NONE")
url = "https://httpbin.ceshiren.com/get"
# 发送HTTPS请求
resp = pm_https.request(method='GET', url=url)
print(json.dumps(resp.data.decode('utf-8')))
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。