Python Request用法|完整指南|请求库核心技巧与实战解析
一、Python Request用法总览
Python requests库是Python社区中用于发送HTTP请求的第三方库,它以简洁、优雅的设计哲学,成为网络请求开发的首选工具。与内置的urllib相比,requests的API设计更贴近人类直觉,极大降低了网络编程的学习门槛。
在爬虫开发、API接口测试、自动化运维、Web服务集成等场景中,Python requests用法已成为必备技能。其核心特性包括:
- 支持HTTP/1.1所有请求方法(GET、POST、PUT、DELETE、HEAD、OPTIONS等)
- 自动处理URL编码与解码
- 支持会话保持(Session)与Cookie管理
- 内置连接池与连接复用机制
- 完善的SSL证书验证与超时控制
- 支持代理、认证、重定向等高级功能
自2011年发布以来,requests已累计获得超200万GitHub Stars,被广泛应用于Django、Flask、Scrapy等主流框架的底层依赖中,堪称Python网络编程的“瑞士军刀”。
二、Python Request用法安装与环境配置
推荐使用pip安装:
pip install requests
若需指定版本(如兼容旧项目),可添加版本号:
pip install requests==2.31.0
验证安装是否成功:
python -c "import requests; print(requests.__version__)"
正常输出版本号(如2.31.0)即表示安装成功。若报错,请检查Python环境变量或网络代理设置。
requests库依赖以下核心组件:
- urllib3:底层HTTP客户端库
- certifi:CA证书集合,用于SSL验证
- charset-normalizer:自动检测响应编码
- idna:支持国际化域名(IDN)解析
安装时pip会自动安装上述依赖。如需手动检查依赖版本:
pip show requests urllib3 certifi charset-normalizer idna
建议保持版本兼容性,避免因依赖冲突导致运行异常。
三、Python Request用法基础操作
GET请求用于获取资源,是最常见的HTTP方法。以下是基础用法:
import requests
url = "https://httpbin.org/get"
response = requests.get(url)
print(f"状态码: {response.status_code}")
print(f"响应头: {response.headers['Content-Type']}")
print(f"响应内容: {response.text[:200]}...
响应对象常用属性:
status_code:HTTP状态码headers:响应头字典text:响应内容(字符串)content:响应内容(二进制)json():解析JSON响应(需确保响应为有效JSON)
通过params参数传递查询参数,自动完成URL编码:
params = {"q": "python request用法", "page": 2}
response = requests.get("https://httpbin.org/get", params=params)
print(response.url) # https://httpbin.org/get?q=python+request%E7%94%A8%E6%B3%95&page=2
注意:参数值中的中文会自动编码为UTF-8格式的URL编码(如“用法”→“%E7%94%A8%E6%B3%95”)。
POST请求用于提交数据,支持表单与JSON格式:
# 表单数据
data = {"username": "test", "password": "123456"}
response = requests.post("https://httpbin.org/post", data=data)
# JSON数据
json_data = {"name": "Alice", "age": 25}
response = requests.post("https://httpbin.org/post", json=json_data)
差异说明:
data参数发送表单数据(Content-Type: application/x-www-form-urlencoded)json参数发送JSON数据(Content-Type: application/json),自动序列化并设置请求头
针对不同响应类型,requests提供多种解析方式:
直接获取响应文本,自动按编码解码:
response = requests.get("https://httpbin.org/html")
print(response.text) # 自动按Content-Type中的charset解码
若服务器未指定编码,可手动指定:
response.encoding = 'utf-8' print(response.text)
直接解析JSON响应,返回Python字典:
response = requests.get("https://httpbin.org/json")
data = response.json()
print(data.keys()) # dict_keys(['slideshow'])
异常处理:若响应非JSON格式,会抛出JSONDecodeError:
try:
data = response.json()
except ValueError:
print("响应不是有效的JSON格式")
获取原始二进制数据(适用于图片、文件下载):
response = requests.get("https://httpbin.org/image/png")
with open("image.png", "wb") as f:
f.write(response.content)
四、Python Request用法进阶技巧
通过headers参数设置自定义请求头,常用于模拟浏览器或传递认证信息:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"Authorization": "Bearer token123"
}
response = requests.get("https://httpbin.org/headers", headers=headers)
注意事项:
- 某些请求头(如Content-Length、Host)由requests自动设置,不可覆盖
- User-Agent常用于反爬绕过,但过度伪装可能触发反爬策略
为避免请求长时间挂起,需设置超时时间:
response = requests.get("https://httpbin.org/delay/3", timeout=2) # 2秒超时
超时分为连接超时(connect timeout)和读取超时(read timeout):
response = requests.get("https://httpbin.org/delay/3", timeout=(3.05, 2.5))
重试机制需结合urllib3 Retry组件实现:
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retry = Retry(total=3, backoff_factor=0.3, status_forcelist=[500, 502, 503])
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get("https://httpbin.org/status/500")
使用stream=True参数避免一次性加载大文件至内存:
with requests.get("https://httpbin.org/stream/20", stream=True) as r:
r.raise_for_status()
with open("large_file.txt", "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
关键点:
stream=True禁用自动内容解码iter_content(chunk_size)分块读取响应体- 使用with确保连接自动关闭
五、Python Request用法异常处理
requests库定义了完整的异常层次结构:
requests.exceptions.RequestException:所有异常的基类Timeout:超时异常ConnectionError:连接异常(DNS失败、拒绝连接等)HTTPError:HTTP状态码异常TooManyRedirects:重定向次数过多
标准异常处理模式:
try:
response = requests.get("https://httpbin.org/status/404", timeout=5)
response.raise_for_status()
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as e:
print(f"HTTP错误: {e}")
except requests.exceptions.RequestException as e:
print(f"请求异常: {e}")
注意:raise_for_status()在状态码非2xx时主动抛出HTTPError。
以下代码可同时处理状态码与异常:
def safe_request(url, **kwargs):
try:
response = requests.get(url, **kwargs)
response.raise_for_status()
return response
except requests.exceptions.HTTPError as e:
print(f"HTTP {response.status_code}: {e}")
return None
except Exception as e:
print(f"请求失败: {e}")
return None
此函数可安全处理网络异常与HTTP错误,避免程序崩溃。
六、Python Request用法代理设置
通过proxies参数设置代理服务器:
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080"
}
response = requests.get("https://httpbin.org/ip", proxies=proxies)
支持带认证的代理:
proxies = {
"http": "http://user:pass@10.10.1.10:3128",
"https": "http://user:pass@10.10.1.10:1080"
}
绕过代理的请求(如本地服务):
proxies = {"http": None, "https": None}
response = requests.get("http://localhost:8000", proxies=proxies)
需安装socks依赖:pip install requests[socks]
proxies = {
"http": "socks5://10.10.1.10:1080",
"https": "socks5://10.10.1.10:1080"
}
response = requests.get("https://httpbin.org/ip", proxies=proxies)
SOCKS代理适用于需要更底层网络控制的场景,如Tor网络。
七、Python Request用法会话管理
Session用于保持连接复用、Cookie持久化及全局配置:
session = requests.Session()
# 全局设置请求头
session.headers.update({"User-Agent": "Custom-Agent/1.0"})
# 登录获取Cookie
login_data = {"user": "admin", "pass": "secret"}
session.post("https://httpbin.org/post", data=login_data)
# 后续请求自动携带Cookie
response = session.get("https://httpbin.org/cookies")
优势:
- 自动复用TCP连接,提升性能
- 自动管理Cookie,支持会话保持
- 可设置全局参数(headers、auth、proxies)
推荐使用with语句确保Session正确关闭:
with requests.Session() as session:
session.get("https://httpbin.org/get")
# 自动关闭连接池
避免连接泄漏导致资源耗尽。
八、Python Request用法SSL证书验证
requests默认启用SSL证书验证,使用certifi提供的CA证书:
response = requests.get("https://httpbin.org/get") # 验证通过
验证失败时抛出SSLError:
response = requests.get("https://self-signed.badssl.com/")
# SSLError: certificate verify failed
通过verify参数指定自定义CA证书:
response = requests.get("https://example.com", verify="/path/to/ca-bundle.crt")
禁用验证(仅测试环境):
response = requests.get("https://example.com", verify=False)
# 警告:忽略SSL证书验证存在安全风险!
安全建议:生产环境禁止禁用SSL验证,防止中间人攻击。
九、Python Request用法异步并发
requests本身是同步库,异步场景需结合aiohttp或使用线程池:
import asyncio
from concurrent.futures import ThreadPoolExecutor
import requests
def fetch(url):
return requests.get(url).text
async def main():
urls = ["https://httpbin.org/get"] * 5
loop = asyncio.get_event_loop()
with ThreadPoolExecutor(max_workers=5) as pool:
tasks = [loop.run_in_executor(pool, fetch, url) for url in urls]
results = await asyncio.gather(*tasks)
print(f"完成 {len(results)} 个请求")
更推荐使用原生异步库aiohttp:
import aiohttp
import asyncio
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, "https://httpbin.org/get") for _ in range(5)]
results = await asyncio.gather(*tasks)
print(f"完成 {len(results)} 个请求")
十、Python Request用法性能优化
Session自动管理连接池,避免重复建立TCP连接:
session = requests.Session()
for i in range(10):
session.get("https://httpbin.org/get") # 复用连接
对比:每次requests.get()都会新建连接,性能较低。
合理设置超时时间,避免长时间等待:
# 连接超时3秒,读取超时2秒 response = requests.get(url, timeout=(3.05, 2.5))
重试策略建议:网络波动场景可重试2-3次,每次指数退避。
requests自动处理gzip/deflate压缩:
response = requests.get(url) # 自动解压
print(response.headers.get("Content-Encoding")) # 可能为'gzip'
服务端未声明编码时,可通过Content-Encoding手动指定。
十一、Python Request用法高频问答
A:检查是否错误使用了data参数。JSON数据需用json参数:
# 错误写法 requests.post(url, data=json.dumps(data)) # 未设置Content-Type # 正确写法 requests.post(url, json=data) # 自动设置Content-Type: application/json
A:使用response.raw属性,但需启用stream=True:
response = requests.get(url, stream=True) raw_data = response.raw.read(100) # 读取前100字节
A:通过allow_redirects参数控制:
# 禁用重定向
response = requests.get("https://httpbin.org/redirect/1", allow_redirects=False)
print(response.status_code) # 302
print(response.headers["Location"]) # 重定向目标
A:使用环境变量NO_PROXY:
import os
os.environ["NO_PROXY"] = "localhost,127.0.0.1,.example.com"
requests.get("http://localhost:8000") # 不使用代理