Python-Requests 库详解

一、Requests 库简介

Requests 是 Python 生态中 ​最广泛使用的 HTTP 客户端库,以「人类友好」为核心设计理念,简化了 HTTP 协议交互的复杂性。其核心价值包括:

  1. 极简 API:通过 requests.get()post() 等函数实现复杂网络操作,代码量比原生 urllib 减少 70% 以上。
  2. 全协议支持:覆盖 GET、POST、PUT、DELETE 等主流 HTTP 方法,适配 RESTful API、WebSocket 等场景。
  3. 高效稳定:内置连接池复用、自动重试、超时控制等机制,支持每秒 1000+ 次高并发请求。
  4. 生态兼容:无缝对接 BeautifulSoup(网页解析)、Pandas(数据处理)、Flask(服务测试)等工具链。
二、安装与环境配置

bash

# 基础安装(Python 3.7+ 环境)  
pip install requests  

# 国内镜像加速安装  
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests  

验证安装

python

import requests  
print(requests.__version__)  # 输出示例:2.31.0  

三、核心功能与常用函数
1. HTTP 基础请求方法
函数功能描述示例代码
​**requests.get()**发送 GET 请求(数据获取场景)response = requests.get("https://api.github.com")
​**requests.post()**发送 POST 请求(表单提交/API 调用)requests.post("https://httpbin.org/post", data={"key": "value"})
​**requests.put()**发送 PUT 请求(资源更新)requests.put("https://api.example.com/data/1", json={"name": "Kimi"})
​**requests.delete()**发送 DELETE 请求(资源删除)requests.delete("https://api.example.com/data/1")
​**requests.Session()**创建会话对象(保持 Cookies 和 TCP 连接复用,提升性能)with requests.Session() as s: s.get("https://example.com")
2. 请求参数与定制化
  • 查询参数传递

    python

    params = {"q": "Python", "page": 2}  
    response = requests.get("https://search.example.com", params=params)  

    生成 URL:https://search.example.com?q=Python&page=2 

  • 请求头定制

    python

    headers = {"User-Agent": "Mozilla/5.0", "Authorization": "Bearer YOUR_TOKEN"}  
    requests.get("https://api.example.com", headers=headers)  

    模拟浏览器行为或身份验证 

  • JSON 数据提交

    python

    requests.post("https://api.example.com/login", json={"username": "admin", "password": "secret"})  

    自动设置 Content-Type: application/json 

3. 响应处理与解析

属性/方法功能描述示例代码
​**response.status_code**获取 HTTP 状态码(如 200 表示成功,404 资源未找到)if response.status_code == 200: print("成功")
​**response.text**获取响应内容(自动解码文本,如 HTML/XML)print(response.text[:500]) # 截取前500字符
​**response.json()**解析 JSON 响应为 Python 字典或列表data = response.json(); print(data["temperature"])
​**response.headers**获取响应头信息(如服务器类型、缓存策略)print(response.headers["Content-Type"])
​**response.raise_for_status()**自动抛出异常(状态码非 200 时触发)try: response.raise_for_status() except requests.HTTPError: ...

4. 高级功能
  • 文件上传与下载

    python

    # 上传文件  
    files = {"file": open("report.pdf", "rb")}  
    requests.post("https://api.example.com/upload", files=files)[4,6](@ref)  
    
    # 流式下载大文件  
    with requests.get("https://example.com/large_video.mp4", stream=True) as r:  
        with open("video.mp4", "wb") as f:  
            for chunk in r.iter_content(chunk_size=8192):  
                f.write(chunk)  
  • 超时与重试策略

    python

    from requests.adapters import HTTPAdapter  
    from urllib3.util.retry import Retry  
    
    retry = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503])  
    adapter = HTTPAdapter(max_retries=retry)  
    session = requests.Session()  
    session.mount("https://", adapter)  
    session.get("https://unstable-api.com", timeout=5)  # 超时5秒,重试3次[4,6](@ref)  

四、应用场景与实战案例
  1. 数据采集与爬虫

    • 抓取新闻标题:requests.get() + BeautifulSoup 解析 HTML
    • 动态内容加载:配合 Selenium 处理 JavaScript 渲染页面
  2. API 集成开发

    • 调用天气接口:requests.get("https://weather-api.com?city=北京")
    • 对接 ChatGPT:发送 JSON 请求并处理流式响应
  3. 自动化测试

    • 验证 REST API 功能:断言响应状态码和数据格式
    • 压力测试:多线程并发发送请求(需结合 concurrent.futures
  4. 企业级应用

    • 财务报表批量下载:会话保持 + 定时任务
    • 跨系统数据同步:OAuth 认证 + POST/PUT 方法

五、注意事项与优化技巧
  1. 安全规范

    • 敏感数据(如 API Key)避免硬编码,使用环境变量管理
    • 启用 HTTPS 并验证证书:verify=True(默认)
  2. 性能调优

    • 复用 Session 对象减少 TCP 握手开销
    • 设置合理超时:timeout=10 防止阻塞主线程
  3. 异常处理

    python

    try:  
        response = requests.get(url, timeout=5)  
        response.raise_for_status()  
    except requests.Timeout:  
        print("请求超时")  
    except requests.ConnectionError:  
        print("网络连接失败")  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值