当前位置:首页 > Python > 正文

Python requests库教程 - 如何检查HTTP请求 | 网络请求调试指南

Python requests库检查HTTP请求完全指南

学习使用Python的requests库检查HTTP请求是网络爬虫开发和API调试的关键技能。本教程将详细演示如何检查请求头、参数、响应状态等关键信息。

一、安装requests库

pip install requests

二、基本请求检查

获取请求状态码和响应头信息:

import requests

response = requests.get('https://httpbin.org/get')
print(f"状态码: {response.status_code}")  # 200
print(f"响应头: {response.headers}")     # 查看服务器返回的头部信息

三、检查请求头

查看发送的请求头信息:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'Accept-Language': 'zh-CN'
}
response = requests.get('https://httpbin.org/headers', headers=headers)

# 检查实际发送的请求头
print(f"请求头: {response.json()['headers']}")

四、检查请求参数

GET请求参数检查:

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

# 验证请求参数
print(f"请求URL: {response.url}")  # https://httpbin.org/get?key1=value1&key2=value2
print(f"请求参数: {response.json()['args']}")

POST请求数据检查:

data = {'username': 'admin', 'password': 'secret'}
response = requests.post('https://httpbin.org/post', data=data)

# 检查发送的表单数据
print(f"请求数据: {response.json()['form']}")

五、重定向跟踪

检查请求重定向历史:

response = requests.get('http://github.com', allow_redirects=True)

print(f"最终URL: {response.url}")
print(f"重定向历史: {[r.url for r in response.history]}

六、完整请求检查示例

def inspect_request(url, method='GET', **kwargs):
    """
    打印请求详细信息
    """
    methods = {
        'GET': requests.get,
        'POST': requests.post,
        'PUT': requests.put,
        'DELETE': requests.delete
    }
    
    response = methods[method](url, **kwargs)
    
    print("===== 请求信息 =====")
    print(f"方法: {method}")
    print(f"URL: {response.url}")
    print(f"状态码: {response.status_code}")
    
    if response.request.headers:
        print("\n===== 请求头 =====")
        for k, v in response.request.headers.items():
            print(f"{k}: {v}")
    
    if response.request.body:
        print("\n===== 请求体 =====")
        print(response.request.body.decode('utf-8'))
    
    return response

# 使用示例
inspect_request(
    'https://httpbin.org/post',
    method='POST',
    data={'test': 'data'},
    headers={'Custom-Header': 'value'}
)

七、常见问题排查

  • 400 Bad Request:检查请求参数格式是否正确
  • 401 Unauthorized:验证认证信息(API密钥/token)
  • 403 Forbidden:检查User-Agent和Referer头
  • 404 Not Found:确认URL地址是否正确
  • 429 Too Many Requests:添加请求延迟或使用代理IP

最佳实践建议

  • 始终检查response.status_code
  • 使用response.request访问原始请求对象
  • 调试时使用httpbin.org测试服务
  • 复杂请求使用Session对象保持状态

发表评论