使用 requests 和 httpx 发起 HTTP 请求
获取网页,并处理重定向、会话和标头。
使用 requests 和 httpx 发起 HTTP 请求 是 CoddyKit 上的免费 Python Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。
requests 库
requests 是标准的同步 HTTP 库。它简单、经过充分验证,非常适合脚本和一次性 API 调用。
# pip install requests
import requests
r = requests.get("https://api.github.com/users/octocat")
print(r.status_code) # 200
print(r.json()["login"]) # octocat查询参数和请求头
使用 params= 传递查询参数,使用 headers= 传递自定义请求头。
import requests
r = requests.get(
"https://api.example.com/search",
params={"q": "python", "page": 1},
headers={"Authorization": "Bearer my-token"}
)
print(r.url) # full URL with query string使用 JSON 请求体发送 POST
使用 json= 发送 JSON 数据;requests 会自动设置 Content-Type: application/json。
import requests
r = requests.post(
"https://api.example.com/users",
json={"name": "Alice", "email": "alice@example.com"}
)
print(r.status_code) # 201
print(r.json())会话对象
使用 requests.Session 在多个请求之间持久化请求头、Cookie 和连接池。
import requests
with requests.Session() as s:
s.headers.update({"Authorization": "Bearer token"})
users = s.get("https://api.example.com/users").json()
profile = s.get("https://api.example.com/me").json()超时和重试
始终设置超时时间。将 urllib3.util.retry.Retry 与 HTTPAdapter 结合使用,以实现自动重试。
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
s = requests.Session()
retry = Retry(total=3, backoff_factor=1)
s.mount("https://", HTTPAdapter(max_retries=retry))
r = s.get("https://api.example.com/data", timeout=5)处理错误
调用 r.raise_for_status(),在响应状态为 4xx/5xx 时引发 HTTPError。
import requests
try:
r = requests.get("https://api.example.com/data")
r.raise_for_status()
data = r.json()
except requests.HTTPError as e:
print(f"HTTP error: {e.response.status_code}")
except requests.ConnectionError:
print("Network unreachable")下载文件
使用 stream=True 流式下载大型文件,避免将全部内容加载到内存中。
import requests
with requests.get("https://example.com/large.zip", stream=True) as r:
r.raise_for_status()
with open("large.zip", "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)httpx——现代异步 HTTP
httpx 与 requests 具有相同的 API,同时支持异步操作。对于 FastAPI 应用和异步工作流,请使用它。
# pip install httpx
import httpx
# Synchronous:
r = httpx.get("https://httpbin.org/get")
print(r.json())
# Asynchronous:
import asyncio
async def main():
async with httpx.AsyncClient() as c:
r = await c.get("https://httpbin.org/get")
print(r.json())
asyncio.run(main())httpx AsyncClient
在多个请求之间共享一个 AsyncClient,以使用连接池。在启动时创建它,在关闭时关闭它。
import httpx, asyncio
CLIENT: httpx.AsyncClient | None = None
async def startup():
global CLIENT
CLIENT = httpx.AsyncClient(timeout=10)
async def shutdown():
await CLIENT.aclose()身份验证辅助工具
requests 和 httpx 都支持身份验证辅助工具:使用 auth=(user, pass) 进行 Basic 身份验证,使用自定义 Auth 类进行令牌身份验证。
import httpx
class BearerAuth(httpx.Auth):
def __init__(self, token): self.token = token
def auth_flow(self, request):
request.headers["Authorization"] = f"Bearer {self.token}"
yield request
async with httpx.AsyncClient(auth=BearerAuth("my-token")) as c:
r = await c.get("https://api.example.com/me")在测试中模拟 HTTP
使用 respx(用于 httpx)或 responses(用于 requests)在测试中模拟 HTTP 调用。
# pip install respx
import httpx, respx, asyncio
@respx.mock
async def test_api():
respx.get("https://api.example.com/users").mock(
return_value=httpx.Response(200, json=[{"id":1}])
)
async with httpx.AsyncClient() as c:
r = await c.get("https://api.example.com/users")
assert r.json() == [{"id": 1}]快速检查
response.raise_for_status() 的作用是什么?
回顾
使用 requests 处理同步 HTTP。需要异步操作时使用 httpx。始终设置超时时间,使用会话复用连接,调用 raise_for_status(),并流式下载大型文件。在测试中使用 respx 或 responses 模拟 HTTP。
常见问题解答
「使用 requests 和 httpx 发起 HTTP 请求」课时是免费的吗?
是的 — 「使用 requests 和 httpx 发起 HTTP 请求」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。
「使用 requests 和 httpx 发起 HTTP 请求」这节课中我会学到什么?
获取网页,并处理重定向、会话和标头。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「使用 requests 和 httpx 发起 HTTP 请求」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python Academy 课中编写并运行代码吗?
能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 requests 和 httpx 发起 HTTP 请求
- 使用 BeautifulSoup 解析 HTML
- 构建 Scrapy 爬虫
- 处理 JavaScript 与反爬措施