Python Requests库完全指南 - 详解

Python requests 库详解

Python requests 库是 HTTP 客户端库的黄金标准,提供了简洁而强大的 API 用于发送 HTTP 请求。以下通过丰富代码示例展示其核心功能。

基本 GET 请求

发送 GET 请求并处理响应是最基础的操作:

import requests
response = requests.get('https://api.github.com')
print(response.status_code)  # 200
print(response.json())  # 解析JSON响应
print(response.headers['Content-Type'])  # application/json

带参数的请求

查询参数可以通过 params 字典传递:

params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url)  # https://httpbin.org/get?key1=value1&key2=value2

POST 请求与数据提交

发送表单数据使用 data 参数:

data = {'key': 'value'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json()['form'])  # {'key': 'value'}

发送 JSON 数据使用 json 参数:

json_data = {'name': 'John', 'age': 30}
response = requests.post('https://httpbin.org/post', json=json_data)
print(response.json()['json'])  # {'name': 'John', 'age': 30}

文件上传

通过 files 参数上传文件:

files = {'file': open('example.txt', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)
print(response.json()['files']['file'])  # 文件内容

自定义请求头

设置自定义请求头:

headers = {'User-Agent': 'my-app/1.0', 'X-Test': 'true'}
response = requests.get('https://httpbin.org/headers', headers=headers)
print(response.json()['headers'])

处理 Cookies

读取和设置 Cookies:

response = requests.get('https://httpbin.org/cookies/set?name=value')
print(response.cookies['name'])  # 'value'
cookies = dict(cookie_name='cookie_value')
response = requests.get('https://httpbin.org/cookies', cookies=cookies)
print(response.json()['cookies'])  # {'cookie_name': 'cookie_value'}

会话对象

使用 Session 保持持久性设置:

session = requests.Session()
session.headers.update({'X-Test': 'true'})
response = session.get('https://httpbin.org/headers')
print(response.json()['headers']['X-Test'])  # 'true'

超时设置

为请求设置超时:

try:
    response = requests.get('https://httpbin.org/delay/3', timeout=2)
except requests.exceptions.Timeout:
    print("请求超时")

代理配置

通过代理发送请求:

proxies = {'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080'}
response = requests.get('https://httpbin.org/ip', proxies=proxies)
print(response.json())

错误处理

捕获常见异常:

try:
    response = requests.get('https://invalid.url')
except requests.exceptions.RequestException as e:
    print(f"请求失败: {e}")

响应内容处理

处理不同格式的响应内容:

response = requests.get('https://httpbin.org/image/png')
with open('image.png', 'wb') as f:
    f.write(response.content)  # 二进制内容
response = requests.get('https://httpbin.org/encoding/utf8')
print(response.text)  # 文本内容

高级用法

使用钩子函数处理请求:

def print_url(r, *args, **kwargs):
    print(r.url)
hooks = {'response': print_url}
requests.get('https://httpbin.org', hooks=hooks)

性能优化

使用流式请求处理大文件:

response = requests.get('https://httpbin.org/stream/20', stream=True)
for line in response.iter_lines():
    if line:
        print(line.decode('utf-8'))

以上示例覆盖了 requests 库的主要功能,包括基本请求、参数处理、数据提交、文件操作、会话管理、错误处理等高级特性。该库简洁的 API 设计使其成为 Python 开发者处理 HTTP 请求的首选工具。

posted on 2025-10-27 11:58  wgwyanfs  阅读(2)  评论(0)    收藏  举报

导航