位置: 文档库 > Python > 详解Python中Requests库的用法

详解Python中Requests库的用法

吴京 上传于 2022-01-24 09:35

《详解Python中Requests库的用法》

Python的Web开发及网络数据抓取领域,Requests库堪称"瑞士军刀"般的存在。作为Python官方推荐的HTTP客户端库,它以简洁的API设计、强大的功能扩展性和良好的兼容性,成为开发者处理HTTP请求的首选工具。本文将从基础用法到高级技巧,系统解析Requests库的核心功能,帮助读者构建高效稳定的网络通信程序。

一、Requests库核心特性

相较于Python内置的urllib库,Requests库通过以下特性显著提升开发效率:

  • 直观的API设计:使用自然语言命名方法(如get()、post())
  • 自动内容解码:自动处理响应内容的编码转换
  • 会话保持:通过Session对象实现跨请求的Cookie管理
  • 连接池支持:内置连接复用机制提升性能
  • 丰富的响应对象:提供状态码、响应头、二进制数据等便捷访问接口

二、基础请求操作

1. 发送简单请求

最基本的GET请求只需一行代码:

import requests
response = requests.get('https://www.example.com')

POST请求示例:

data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=data)

2. 请求参数处理

通过params参数传递URL查询字符串:

params = {'q': 'python', 'page': 1}
response = requests.get('https://api.github.com/search', params=params)

生成的URL会自动编码特殊字符:

print(response.url)  # 输出: https://api.github.com/search?q=python&page=1

3. 响应对象解析

响应对象包含以下常用属性:

  • status_code:HTTP状态码(200表示成功)
  • headers:响应头字典
  • text:解码后的文本内容
  • content:原始字节内容
  • json():自动解析JSON响应
if response.status_code == 200:
    print(response.text[:100])  # 打印前100个字符
    json_data = response.json()  # 解析JSON响应

三、高级功能实现

1. 会话管理(Session)

Session对象可以跨请求保持Cookie和配置:

with requests.Session() as session:
    session.auth = ('user', 'pass')  # 设置认证
    response1 = session.get('https://api.example.com/profile')
    response2 = session.get('https://api.example.com/settings')  # 自动携带之前的Cookie

2. 自定义请求头

通过headers参数模拟浏览器请求:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'Accept': 'application/json'
}
response = requests.get(url, headers=headers)

3. 超时设置

防止请求长时间挂起:

try:
    response = requests.get(url, timeout=5)  # 5秒超时
except requests.exceptions.Timeout:
    print('请求超时')

4. 文件上传

使用files参数上传文件:

files = {'file': open('report.xlsx', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)

5. 代理设置

配置HTTP/HTTPS代理:

proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://20.20.1.20:1080'
}
response = requests.get(url, proxies=proxies)

四、异常处理机制

Requests库定义了完整的异常体系:

  • requests.exceptions.RequestException:所有异常基类
  • ConnectionError:连接错误
  • HTTPError:HTTP错误(4xx/5xx)
  • Timeout:超时错误
  • TooManyRedirects:重定向过多

推荐使用try-except块处理异常:

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()  # 如果状态码不是200,抛出HTTPError
except requests.exceptions.HTTPError as errh:
    print(f"HTTP错误: {errh}")
except requests.exceptions.ConnectionError as errc:
    print(f"连接错误: {errc}")
except requests.exceptions.Timeout as errt:
    print(f"超时错误: {errt}")
except requests.exceptions.RequestException as err:
    print(f"其他错误: {err}")

五、性能优化技巧

1. 连接复用

通过Session对象自动管理连接池:

session = requests.Session()
for _ in range(10):
    session.get('https://example.com')  # 复用TCP连接

2. 流式响应

处理大文件时使用流式下载:

with requests.get(large_file_url, stream=True) as r:
    with open('large_file.zip', 'wb') as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

3. 并发请求

结合asyncio实现异步请求(需配合aiohttp等库):

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        
asyncio.run(main())

六、安全实践

1. HTTPS验证

默认验证SSL证书,可通过verify参数禁用(不推荐):

response = requests.get('https://example.com', verify=False)  # 禁用证书验证

更安全的做法是指定证书路径:

response = requests.get('https://example.com', verify='/path/to/cert.pem')

2. 敏感信息保护

避免在代码中硬编码凭证,建议使用环境变量:

import os
auth = (os.getenv('API_USER'), os.getenv('API_PASSWORD'))

七、实战案例解析

案例1:GitHub API交互

import requests

def get_repo_info(owner, repo):
    url = f'https://api.github.com/repos/{owner}/{repo}'
    headers = {'Accept': 'application/vnd.github.v3+json'}
    
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        data = response.json()
        return {
            'stars': data['stargazers_count'],
            'forks': data['forks_count'],
            'language': data['language']
        }
    except requests.exceptions.RequestException as e:
        print(f"获取仓库信息失败: {e}")
        return None

print(get_repo_info('requests', 'requests'))

案例2:分页数据获取

def fetch_paginated_data(base_url, max_pages=5):
    all_data = []
    page = 1
    
    while page 

八、常见问题解决方案

问题1:SSL证书错误

解决方案:

  • 更新证书包:pip install certifi
  • 指定证书路径:verify='/etc/ssl/certs/ca-certificates.crt'
  • 临时禁用验证(仅测试环境):verify=False

问题2:请求被拒绝(403 Forbidden)

可能原因及解决方案:

  • 缺少User-Agent:添加浏览器风格的User-Agent
  • 频率限制:添加延迟或使用代理IP
  • 需要认证:添加API密钥或OAuth令牌

问题3:慢速响应

优化建议:

  • 设置合理的超时时间
  • 使用会话保持连接
  • 考虑使用CDN或镜像源
  • 实现重试机制(需谨慎避免雪崩)

九、Requests库生态扩展

Requests库拥有丰富的第三方扩展:

  • Requests-OAuthlib:OAuth认证支持
  • Requests-HTML:HTML解析功能
  • Requests-Toolbelt:额外工具集合
  • CacheControl:响应缓存

安装扩展库示例:

pip install requests-oauthlib requests-html

关键词:Python、Requests库、HTTP请求网络编程、API交互、会话管理、异常处理性能优化、安全实践

简介:本文系统解析Python Requests库的完整用法,涵盖基础请求操作、高级功能实现、异常处理机制、性能优化技巧及安全实践,通过实战案例演示GitHub API交互和分页数据获取,并整理常见问题解决方案与生态扩展信息,帮助开发者构建高效稳定的网络通信程序。

《详解Python中Requests库的用法.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档