1. urllib3 概述
官方文檔:https://urllib3.readthedocs.io/en/stable/
Urllib3是一個(gè)功能強(qiáng)大,條理清晰,用于HTTP客戶端的Python庫,許多Python的原生系統(tǒng)已經(jīng)開始使用urllib3。Urllib3提供了很多python標(biāo)準(zhǔn)庫里所沒有的重要特性:
- 線程安全
- 連接池管理
- 客戶端 SSL/TLS 驗(yàn)證
- 支持 HTTP 和 SOCKS 代理
- ……
2. urllib3 安裝
通過 pip 安裝
pip install urllib3
3. urllib3 發(fā)送 HTTP 請(qǐng)求
- 導(dǎo)入
urllib3
模塊 - 創(chuàng)建
PoolManager
實(shí)例 - 調(diào)用
request()
方法
import urllib3
def test_HTTP():
# 創(chuàng)建連接池對(duì)象,默認(rèn)會(huì)校驗(yàn)證書
pm = urllib3.PoolManager()
# 發(fā)送HTTP請(qǐng)求
res = pm.request(method='GET', url="http://httpbin.org/robots.txt")
print(type(res))
"""
打印結(jié)果:
<class 'urllib3.response.HTTPResponse'>
"""
4. urllib3 HTTPResponse 對(duì)象
- status 屬性
- headers 屬性
- data 屬性
import urllib3
def test_response():
# 創(chuàng)建連接池對(duì)象
pm = urllib3.PoolManager()
# 發(fā)送請(qǐng)求
resp = pm.request(method='GET', url="http://httpbin.org/ip")
print(resp.status) # 查看響應(yīng)狀態(tài)狀態(tài)碼
print(resp.headers) # 查看響應(yīng)頭信息
print(resp.data) # 查看響應(yīng)原始二進(jìn)制信息
5. urllib3 解析響應(yīng)內(nèi)容
- 二進(jìn)制響應(yīng)內(nèi)容解碼
- JSON 字符串
import urllib3
import json
def test_response():
pm = urllib3.PoolManager()
resp = pm.request(method='GET', url="http://httpbin.org/ip")
# 獲取二進(jìn)制形式的響應(yīng)內(nèi)容
raw = resp.data
print(type(raw), raw)
# 使用utf-8解碼成字符串
content = raw.decode('utf-8')
print(type(content), content)
# 將JSON字符串解析成字典對(duì)象
dict_obj = json.loads(content)
print(type(dict_obj), dict_obj)
print(dict_obj['origin'])
6. urllib3 request 請(qǐng)求參數(shù)
-
語法:
request(method, url, fields, headers, **)
-
必填
-
method
:請(qǐng)求方式 -
url
:請(qǐng)求地址
-
-
選填
-
headers
:請(qǐng)求頭信息 -
fields
:請(qǐng)求體數(shù)據(jù) -
body
:指定請(qǐng)求體類型 -
tiemout
:設(shè)置超時(shí)時(shí)間
-
7. urllib3 定制請(qǐng)求數(shù)據(jù)
7.1. 定制請(qǐng)求頭信息
- 使用
headers
參數(shù)
import urllib3
import json
def test_headers():
pm = urllib3.PoolManager()
url = "http://httpbin.org/get"
# 定制請(qǐng)求頭
headers = {'School': 'hogwarts'}
resp = pm.request('GET', url, headers=headers)
7.2. 定制查詢字符串參數(shù)
-
fields
參數(shù):適用于GET, HEAD, DELETE
請(qǐng)求 - 拼接
url
:適用于POST, PUT
請(qǐng)求
import urllib3
import json
# GET/HEAD/DELETE 請(qǐng)求
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 請(qǐng)求
def test_urlencode():
# 從內(nèi)置庫urllib的parse模塊導(dǎo)入編碼方法
from urllib.parse import urlencode
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
# POST和PUT請(qǐng)求需要編碼后拼接到URL中
encoded_str = urlencode({'school': 'hogwarts'})
resp = pm.request('POST', url=url+"?"+encoded_str)
7.3. 提交 form 表單數(shù)據(jù)
- 類型
'Content-Type': 'multipart/form-data
- 請(qǐng)求方式:POST、PUT
import urllib3
import json
# POST/PUT 請(qǐng)求
def test_form():
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
fields = {'school': 'hogwarts'}
# fields數(shù)據(jù)會(huì)自動(dòng)轉(zhuǎn)成form格式提交
resp = pm.request('POST', url, fields=fields)
7.4. 提交 JSON 格式數(shù)據(jù)
- 類型:
'Content-Type': 'application/json'
- 請(qǐng)求方式:POST、PUT
import urllib3
import json
def test_json():
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
# 設(shè)定請(qǐng)求體數(shù)據(jù)類型
headers={'Content-Type': 'application/json'}
# JSON文本數(shù)據(jù)
json_str = json.dumps({'school': 'hogwarts'})
resp = pm.request('POST', url, headers=headers, body=json_str)
7.5. timeout :設(shè)置超時(shí)時(shí)間
- 時(shí)間單位:秒
- 值的格式:float 類型
import urllib3
def test_timeout():
pm = urllib3.PoolManager()
# 訪問這個(gè)地址,服務(wù)器會(huì)在3秒后響應(yīng)
url = "http://httpbin.org/delay/3"
# 設(shè)置超時(shí)時(shí)長
resp = pm.request(method='GET', url=url, timeout=4.0)
assert resp.status == 200
8. urllib3 發(fā)送 HTTPS 請(qǐng)求
-
HTTPS 請(qǐng)求默認(rèn)需要校驗(yàn)證書文章來源:http://www.zghlxwxcb.cn/news/detail-648784.html
-
PoolManager 的
cert_reqs
參數(shù)文章來源地址http://www.zghlxwxcb.cn/news/detail-648784.html-
"CERT_REQUIRED"
:需要校驗(yàn) -
"CERT_NONE"
:取消校驗(yàn)
-
import urllib3
import json
def test_HTTPS():
# 創(chuàng)建不校驗(yàn)證書的連接池對(duì)象
pm_https = urllib3.PoolManager(cert_reqs="CERT_NONE")
url = "https://httpbin.ceshiren.com/get"
# 發(fā)送HTTPS請(qǐng)求
resp = pm_https.request(method='GET', url=url)
print(json.dumps(resp.data.decode('utf-8')))
到了這里,關(guān)于【python】(十九)python常用第三方庫——urllib3的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!