ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 安装 requests
  • 基本用法
    • 1. 发送 GET 请求
    • 2. 发送带参数的 GET 请求
    • 3. 发送 POST 请求
  • 主要功能
    • 1. 响应内容处理
    • 2. 自定义请求头
    • 3. 发送 JSON 数据
    • 4. 处理 Cookie
    • 5. 会话对象 (Session)
    • 6. 超时设置
    • 7. 代理设置
  • 高级功能
    • 1. 流式下载大文件
    • 2. 验证 SSL 证书
    • 3. 身份验证
    • 4. 处理重定向
    • 5. 事件钩子
  • 错误处理
  • 性能优化
    • 1. 连接池
    • 2. 流式请求
  • 最佳实践
  • 总结

requests 是 Python 中最流行的 HTTP 客户端库,它简化了 HTTP 请求的发送过程,提供了人性化的 API 接口。

安装 requests #

pip install requests

基本用法 #

1. 发送 GET 请求 #

import requests

response = requests.get('https://api.github.com')
print(response.status_code)  # 打印状态码
print(response.text)        # 打印响应内容

2. 发送带参数的 GET 请求 #

params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url)  # 查看实际请求的URL

3. 发送 POST 请求 #

data = {'key': 'value'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json())  # 将响应解析为JSON

主要功能 #

1. 响应内容处理 #

response = requests.get('https://api.github.com')

# 文本内容
print(response.text)

# 二进制内容
print(response.content)

# JSON内容
print(response.json())

# 原始响应
print(response.raw)

2. 自定义请求头 #

headers = {
    'User-Agent': 'my-app/0.0.1',
    'Authorization': 'Bearer token123'
}
response = requests.get('https://api.github.com', headers=headers)

3. 发送 JSON 数据 #

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

4. 处理 Cookie #

# 发送Cookie
cookies = dict(cookie_key='cookie_value')
response = requests.get('https://httpbin.org/cookies', cookies=cookies)

# 接收Cookie
print(response.cookies['example_cookie_name'])

5. 会话对象 (Session) #

# 创建会话
session = requests.Session()

# 设置会话级参数
session.headers.update({'x-test': 'true'})

# 使用会话发送请求
session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
response = session.get('https://httpbin.org/cookies')

print(response.text)

6. 超时设置 #

try:
    response = requests.get('https://github.com', timeout=0.5)
except requests.exceptions.Timeout:
    print("请求超时")

7. 代理设置 #

proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:1080',
}

requests.get('http://example.org', proxies=proxies)

高级功能 #

1. 流式下载大文件 #

url = "https://example.com/large-file.zip"
response = requests.get(url, stream=True)

with open('large-file.zip', 'wb') as f:
    for chunk in response.iter_content(chunk_size=8192):
        f.write(chunk)

2. 验证 SSL 证书 #

# 默认验证
requests.get('https://github.com', verify=True)

# 禁用验证(不安全)
requests.get('https://github.com', verify=False)

# 使用自定义CA证书
requests.get('https://github.com', verify='/path/to/certfile')

3. 身份验证 #

# 基本认证
from requests.auth import HTTPBasicAuth
requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))

# 简写形式
requests.get('https://api.github.com/user', auth=('user', 'pass'))

# OAuth认证
headers = {'Authorization': 'Bearer token123'}
requests.get('https://api.github.com/user', headers=headers)

4. 处理重定向 #

# 允许重定向(默认)
r = requests.get('http://github.com', allow_redirects=True)

# 禁止重定向
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code)  # 301或302
print(r.headers['Location'])

5. 事件钩子 #

# 定义钩子函数
def print_url(r, *args, **kwargs):
    print(r.url)

# 使用钩子
requests.get('https://httpbin.org', hooks={'response': print_url})

错误处理 #

try:
    response = requests.get('https://api.github.com')
    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. 连接池 #

requests 默认使用 urllib3 的连接池,可以通过 Session 对象复用连接:

session = requests.Session()

for _ in range(10):
    session.get('https://api.github.com')  # 复用TCP连接

2. 流式请求 #

对于大响应,使用流式处理可以节省内存:

response = requests.get('https://example.com/large-file', stream=True)
for line in response.iter_lines():
    print(line)

最佳实践 #

  1. 总是检查响应状态码:使用 response.raise_for_status() 或手动检查
  2. 使用会话对象:当需要发送多个请求到同一主机时
  3. 设置合理的超时:避免程序长时间挂起
  4. 处理异常:捕获并适当处理网络请求可能出现的各种异常
  5. 关闭响应:对于流式响应,确保调用 response.close()

总结 #

requests 库提供了简洁而强大的 HTTP 客户端功能,使得在 Python 中发送 HTTP 请求变得非常简单。无论是简单的 GET 请求还是复杂的 REST API 交互,requests 都能优雅地处理。通过掌握其核心功能和高级特性,你可以高效地与各种 Web 服务进行交互。

访问验证

请输入访问令牌

Token不正确,请重新输入