Python从入门到精通(第61章):Requests库实战

张开发
2026/4/17 8:33:28 15 分钟阅读

分享文章

Python从入门到精通(第61章):Requests库实战
开头导语Python 调 API 用什么?99% 的情况答案是 requests。它把 HTTP 请求封装成直观的方法,把响应封装成对象,代码读起来就像读自然语言。很多人用 requests 就是.get()和.post(),但真正的高手懂得用 Session 复用连接、配超时防卡死、上代理防封禁、加重试抗抖动。本章把 requests 的实用技巧全部讲透。章节摘要本章讲解 Python requests 库的核心用法。requests.get/post/put/delete发送 HTTP 请求,params拼接 URL 参数,data/json发送请求体。Session复用 TCP 连接、共享 Cookie、保持 Header。timeout设置超时防止请求卡死。response对象的status_code/json/text/content分别获取状态码/解析JSON/原始文本/字节内容。requests.adapters.HTTPAdapter配urllib3.util.retry实现自动重试。关键词requests、Session、timeout、params、json、retry、status_code、HTTPAdapter学习目标掌握 requests 的 GET/POST/PUT/DELETE 用法理解 Session 的作用和使用场景掌握超时设置和重试机制能够处理常见的 HTTP 错误先修知识HTTP 协议基础(第51章)环境准备pipinstallrequests快速上手importrequests# GET 请求resp=requests.get("https://httpbin.org/get")print(resp.status_code)print(resp.json())# POST 请求resp=requests.post("https://httpbin.org/post",json={"name":"Ada","age":18}# requests 自动设置 Content-Type: application/json)print(resp.json())# 带参数resp=requests.get("https://httpbin.org/get",params={"name":"Ada","age":18}# 自动拼到 URL)print(resp.url)# https://httpbin.org/get?name=Adaage=18响应对象resp=requests.get("https://httpbin.org/json")resp.status_code# HTTP 状态码(200)resp.text# 响应体原文(str)resp.content# 响应体字节(bytes)resp.json()# 自动解析 JSON(dict/list)resp.headers# 响应头(dict)resp.cookies# 响应的 Cookie(RequestsCookieJar)resp.encoding# 响应编码(从 Content-Type 推断)resp.elapsed# 请求耗时(timedelta)resp.url# 最终请求的 URL(跟随重定向后)resp.request# 请求对象(可查看发送的 headers 等)发送各类数据# URL 查询参数(?key=value)resp=requests.get("https://httpbin.org/get",params={"page":1,"per_page":10})# 表单数据(application/x-www-form-urlencoded)resp=requests.post("https://httpbin.org/post",data={"username":"ada","password":"123456"})# JSON 数据(application/json)resp=requests.post("https://httpbin.org/post",json={"username":"ada","password":"123456"})# 自定义请求头resp=requests.get("https://api.github.com/user",headers={"Authorization":"token ghp_xxxxx","Accept":"application/vnd.github.v3+json"})# 文件上传(multipart/form-data)withopen("report.xlsx","rb")asf:resp=requests.post("https://httpbin.org/post",files={"file":("report.xlsx",f,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")})# 下载文件resp=requests.get("https://httpbin.org/b

更多文章