在Python中发送HTTP请求可通过内置的urllib库或第三方requests库实现,具体选择取决于需求复杂度。以下是两种方法的详细说明及示例:
一、使用内置urllib库(适合基扰胡慧础需求)urllib是Python标准库的一部分,无需安装,但代码较繁琐,适合简单请求。
核心步骤:
- 导入模块:urllib.request(发送请求)、urllib.parse(处理URL参数)。
- 构建请求:通过Request对象设置URL、参数、请求方法(如POST)。
- 发送请求:使用urlopen打开请求并获取响应。
- 解析响应:读取响应内容并解码(如utf-8)。
示例代码(POST请求):
import urllib.requestimport urllib.parseurl = 'http://example.com'params
= {'key1': 'value1', 'key2': 'value2'}data = urllib.parse.urlencode(params).encode('utf-8') # 编码参数req = urllib.request.Request(url, data=data, method='POST') # 构建POST请求with urllib.request.urlopen(req) as response: html = response.read() print(html.decode('utf-8')) # 解码响应内容局限性:
- 处理复杂请求头、Cookies或JSON数据需额外代码。
- 需手动处理URL编码、异常等细节。
二、使用第三方requests库(推荐,适合复杂场景)requests库提供简洁API,支持自动处理编码、会话保持、JSON等,需通过pip install requests安装。
核做棚心优势:
- 简洁语法:一行代码即可发送GET/POST请求。
- 自动处理:自动解码响应内容、支持JSON数据发送/接收。
- 扩展功能:超时缓答设置、异常处理、会话管理、并发请求等。
示例代码(POST请求发送JSON):
import requestsurl = 'https://api.example.com/data'payload
= {'name': 'John', 'age': 30}response = requests.post(url, json=payload) # 自动将字典转为JSON并设置Content-Typeif response.status_code == 200: data = response.json() # 解析JSON响应 print(data)else: print(f"Request failed with status code: {response.status_code}")三、关键技巧与注意事项超时设置避免程序长时间等待,建议设置超时时间(单位:秒):
response = requests.get(url, timeout=5)异常处理捕获网络请求可能出现的异常(如超时、连接错误):
try: response = requests.get(url) response.raise_for_status() # 检查HTTP错误状态码except requests.exceptions.RequestException as e: print(f"An error occurred: {e}")会话管理保持Cookies或会话状态(如登录后访问需认证的页面):
with requests.Session() as session: session.get('http://example.com/login'
) # 登录请求 response = session.get('http://example.com/protected'
) # 访问受保护页面 print(response.text)性能优化
并发请求:使用ThreadPoolExecutor或异步库(如aiohttp)加速多请求:from concurrent.futures import ThreadPoolExecutordef fetch(url): return requests.get(url)urls = ['
http://example.com/page1'
, 'http://example.com/page2'
]with ThreadPoolExecutor(max_workers=5) as executor: responses = list(executor.map(fetch, urls)) for response in responses: print(response.text)缓存响应:减少重复请求,使用requests-cache库:import requests_cacherequests_cache.install_cache('demo_cache', expire_after=300) # 缓存5分钟response = requests.get('
http://example.com'
)print(response.from_cache) # 检查是否从缓存读取
四、总结- 简单需求:使用urllib,无需安装,但代码冗长。
- 复杂场景:优先选择requests,支持JSON、会话、异常处理等高级功能。
- 性能关键场景:结合并发请求与缓存机制优化效率。
根据项目需求灵活选择库,并合理应用超时、异常处理等技巧,可显著提升代码健壮性与执行效率。