Python网络请求怎么写_requests库实战教程

5次阅读

requests发起网络请求分三步:导入库、发请求、取数据;支持get/post、参数传递、文件上传、请求头设置、会话管理及异常处理与超时控制。

Python网络请求怎么写_requests库实战教程

requests 发起网络请求,核心就三步:导入库、发请求、取数据。它比原生 urllib 简洁得多,是 python 网络爬虫和 API 调用的标配。

GET 请求:获取网页或 API 数据

最常用的是 requests.get()。比如抓取一个公开 json 接口

import requests <p>response = requests.get("<a href="https://www.php.cn/link/b2ec3778d61b7fbba65a900aebc41c1a">https://www.php.cn/link/b2ec3778d61b7fbba65a900aebc41c1a</a>") if response.status_code == 200: data = response.json()  # 自动解析 JSON print(data["args"])  # {'name': 'alice', 'age': '25'}
  • 记得检查 response.status_code,200 表示成功,4xx/5xx 是错误
  • response.text字符串response.json() 拿字典(自动解析),response.content 拿原始字节(适合图片、PDF)
  • URL 中的参数可用 params 参数传,更安全清晰:requests.get(url, params={"name": "alice", "age": 25})

POST 请求:提交表单或调用接口

向服务器发送数据,常见于登录、上传、调用 REST API:

data = {"username": "test", "password": "123456"} response = requests.post("https://httpbin.org/post", data=data) print(response.json()["form"])  # {'username': 'test', 'password': '123456'}
  • data= 发送表单格式(application/x-www-form-urlencoded
  • json= 自动序列化并设好 Content-Type: application/jsonrequests.post(url, json={"key": "value"})
  • 上传文件用 files= 参数:files={"file": open("a.txt", "rb")}

带请求头和会话管理:模拟真实浏览器

很多网站会检查 User-Agent,直接请求可能被拒绝:

立即学习Python免费学习笔记(深入)”;

headers = {     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } response = requests.get("https://example.com", headers=headers)
  • 常用头还包括 ReferercookieAccept
  • 需要维持登录态?用 requests.session(),它自动复用 Cookie 和连接:
s = requests.Session() s.get("https://httpbin.org/cookies/set/sessioncookie/123456789") r = s.get("https://httpbin.org/cookies")  # 会带上上面设置的 cookie print(r.json())  # {'cookies': {'sessioncookie': '123456789'}}

异常处理与超时控制:让代码更健壮

网络不稳定,必须捕获异常,否则程序容易崩:

try:     response = requests.get("https://httpbin.org/delay/5", timeout=3) except requests.exceptions.Timeout:     print("请求超时了") except requests.exceptions.ConnectionError:     print("连不上服务器") except requests.exceptions.RequestException as e:     print(f"其他请求错误:{e}")
  • timeout 推荐显式设置,单位秒,可传元组 (连接超时, 读取超时)
  • 统一捕获 requests.RequestException 可覆盖大多数异常类型
  • 避免不加防护地调用 .json(),先用 .ok 或状态码判断响应是否有效

requests 库上手快,但细节决定成败——头怎么设、超时怎么控、异常怎么兜底、会话怎么复用,这些才是真正写好网络请求的关键。不复杂但容易忽略。

text=ZqhQzanResources