HTTP.Client?庫對比與選擇
在 Python 中,除了標準庫 http.client,還有許多功能更強大、使用更便捷的 HTTP 庫。以下是一些常用的庫及其特點:
1. Requests(最流行)
特點:
- 高層 API,簡單易用(requests.get()、requests.post())
- 自動處理 URL 編碼、JSON 解析、會話管理、重定向等
- 廣泛的社區支持和文檔
安裝:
pip install requests |
示例:
import requests # GET 請求 response = requests.get("https://api.example.com/users") data = response.json() ?# 自動解析 JSON # POST 請求 payload = {"name": "test"} response = requests.post("https://api.example.com/users", json=payload) # 帶參數的請求 params = {"page": 1, "limit": 10} response = requests.get("https://api.example.com/search", params=params) # 會話管理(保持 Cookie) session = requests.Session() session.post("https://api.example.com/login", data={"user": "admin"}) session.get("https://api.example.com/dashboard") |
2. aiohttp(異步請求)
特點:
- 基于 asyncio 的異步 HTTP 客戶端 / 服務器
- 適合高并發場景(如爬蟲、API 網關)
- 支持同步和異步兩種使用方式
安裝:
pip install aiohttp |
示例:
import aiohttp import asyncio async def fetch(url): ????async with aiohttp.ClientSession() as session: ????????async with session.get(url) as response: ????????????return await response.json() # 并發請求多個 URL async def main(): ????urls = ["https://api.example.com/users/1", "https://api.example.com/users/2"] ????tasks = [fetch(url) for url in urls] ????results = await asyncio.gather(*tasks) ????print(results) asyncio.run(main()) |
3. httpx(新一代 HTTP 客戶端)
特點:
- 兼容 Requests 的 API,支持同步和異步模式
- 支持 HTTP/2(部分支持 HTTP/3)
- 更好的類型提示和異步支持
安裝:
pip install httpx |
示例:
import httpx # 同步請求 response = httpx.get("https://api.example.com") # 異步請求 async def async_request(): ????async with httpx.AsyncClient() as client: ????????response = await client.get("https://api.example.com") ????????return response.json() # HTTP/2 請求 response = httpx.get("https://http2.akamai.com/demo", http2=True) |
4. urllib.request(標準庫)
特點:
- Python 標準庫的一部分,無需額外安裝
- 功能比 http.client?更高級,但比 Requests 簡單
示例:
from urllib import request, parse # GET 請求 with request.urlopen("https://api.example.com") as response: ????data = response.read().decode() # POST 請求 params = parse.urlencode({"name": "test"}).encode() req = request.Request("https://api.example.com", data=params) with request.urlopen(req) as response: ????data = response.read().decode() |
5. Tornado HTTP Client
特點:
- 高性能異步 HTTP 客戶端(Tornado 框架的一部分)
- 適合構建實時 Web 應用和 API 服務器
安裝:
pip install tornado |
示例:
from tornado import httpclient, ioloop async def fetch_url(): ????client = httpclient.AsyncHTTPClient() ????response = await client.fetch("https://api.example.com") ????print(response.body.decode()) ioloop.IOLoop.current().run_sync(fetch_url) |
6. Requests-HTML
特點:
- 基于 Requests,增加了 HTML 解析功能(類似 BeautifulSoup)
- 支持 JavaScript 渲染(通過 Chromium)
安裝:
pip install requests-html |
示例:
from requests_html import HTMLSession session = HTMLSession() response = session.get("https://example.com") # 查找所有鏈接 links = response.html.find("a") for link in links: ????print(link.text, link.attrs["href"]) # 渲染 JavaScript 內容 response.html.render() print(response.html.html) |
7. HTTPX(與 Requests 兼容的異步庫)
特點:
- 完全兼容 Requests API,同時支持異步編程
- 支持 HTTP/2 和 HTTP/3
- 提供更好的類型提示和錯誤處理
安裝:
pip install httpx |
示例:
import httpx # 同步使用 response = httpx.get("https://api.example.com") print(response.json()) # 異步使用 async def fetch_data(): ????async with httpx.AsyncClient() as client: ????????response = await client.get("https://api.example.com") ????????return response.json() |
庫的選擇建議
場景 | 推薦庫 |
簡單的同步請求 | Requests |
高性能異步請求 | aiohttp / httpx |
無需第三方依賴 | urllib.request |
爬蟲與 HTML 解析 | Requests-HTML |
與 Tornado 框架集成 | Tornado Client |
需要 HTTP/2 支持 | httpx |
對比總結
特性 | http.client | requests | aiohttp | httpx |
是否標準庫 | ? | ? | ? | ? |
異步支持 | ? | ? | ? | ? |
HTTP/2 支持 | ? | ? | ? | ? |
會話管理 | ? | ? | ? | ? |
JSON 自動解析 | ? | ? | ? | ? |
使用難度 | 高 | 低 | 中高 | 低 |
社區活躍度 | 低 | 高 | 中高 | 中高 |
根據項目需求選擇合適的庫,可以大幅提高開發效率。對于大多數場景,推薦優先使用 Requests?或 httpx。