Python 常用第三方庫 urllib3
阿新 • • 發佈:2022-05-05
urllib3 概述
- 執行緒安全
- 連線池管理
- 客戶端 SSL/TLS 驗證
- 支援 HTTP 和 SOCKS 代理
官方文件:https://urllib3.readthedocs.io/en/stable/
urllib3 安裝
- 通過 pip 安裝
pip install urllib3
urllib3 傳送 HTTP 請求
- 匯入
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))
urllib3 HTTPResponse 物件
- status 屬性:響應狀態碼
- headers 屬性
- data 屬性:正文
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) # 檢視響應原始二進位制資訊
urllib3 解析響應內容
-
二進位制響應內容解碼
-
JSON 字串
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'])
urllib3 request 請求引數
- 語法:
request(method, url, fields, headers, **)
- 必填
-
method
:請求方式 -
url
:請求地址
-
- 選填
-
headers
:請求頭資訊 -
fields
:請求體資料 -
body
:指定請求體型別 -
tiemout
:設定超時時間
-
urllib3 定製請求資料
-
定製請求頭資訊
-
使用
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)
urllib3 定製請求資料
-
定製查詢字串引數
-
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)
urllib3 定製請求資料
-
提交 form 表單資料
-
型別
'Content-Type': 'multipart/form-data
-
請求方式:POST、PUT
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)
urllib3 定製請求資料
-
提交 JSON 格式資料
-
型別:
'Content-Type': 'application/json'
-
請求方式:POST、PUT
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
:設定超時時間 -
時間單位:秒
-
值的格式:float 型別
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
urllib3 傳送 HTTPS 請求
-
HTTPS 請求預設需要校驗證書
-
PoolManager 的
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')))