现在需要帮助客户了解如何使用Python的requests库发送HTTP请求。首先,我得回忆一下requests库的基本用法,可能客户是刚开始学习这个库,所以需要从安装开始讲起。
首先,安装部分。客户可能没有安装requests库,所以需要告诉他们用pip安装。不过有时候客户可能已经安装了,但为了全面起见,还是应该包括安装步骤。比如pip install requests,可能还要提醒他们确保pip是最新版本,或者如果遇到权限问题,可以加上--user选项。

接下来是发送GET请求。这是最常见的请求类型,所以应该先介绍。示例代码里要用requests.get(),然后展示如何获取响应状态码和内容。可能需要解释一下status_code和text属性,以及如何判断请求是否成功,比如200 OK的情况。
然后是POST请求。这部分需要解释POST和GET的区别,比如用于提交表单数据。示例中应该包含如何传递data参数,比如字典形式的数据。同时,可能需要提到有时候需要发送JSON数据,这时候可以用json参数而不是data,这样库会自动处理编码和头信息。
URL参数的处理也很重要。比如在GET请求中附加查询参数,可以用params参数,这样requests会自动构建URL,避免手动拼接的麻烦。这里可以举一个例子,比如传递key1=value1和key2=value2,然后显示最终的URL是什么样的。
接下来是请求头部的设置。有些API需要特定的headers,比如User-Agent或者Authorization。这里需要展示如何传递headers字典给get或post方法,并举例说明常见的头字段,比如Content-Type或者Accept。
处理响应内容的部分需要详细一些。比如,获取文本内容用text,但是编码可能有问题,所以可能需要用response.encoding来指定正确的编码。另外,如果是JSON响应,可以直接用response.json()来解析,这样更方便。还可以提到检查状态码是否成功,比如response.raise_for_status()方法,这样可以在出错时抛出异常。
错误处理也是关键。比如网络问题、超时或者无效的URL,这时候requests会抛出异常,比如ConnectionError、Timeout等。应该建议客户使用try-except块来捕获这些异常,并给出示例代码。另外,处理HTTP错误状态码,比如4xx或5xx,可以用response.raise_for_status(),或者手动检查status_code。
高级用法可能包括会话对象、代理设置、超时配置、SSL证书验证等。会话对象可以保持cookie和连接,提高性能。代理设置在某些环境下可能需要,比如公司网络。超时可以防止请求挂起太长时间。SSL验证有时在测试环境需要禁用,但生产环境不建议。
具体案例实操
以下是使用Python的requests
库发送HTTP请求的详细指南,包含基础到进阶的用法:
1. 安装requests库
在终端中运行以下命令安装:
python
pip install requests
2. 发送GET请求
基础用法:获取网页内容
python
import requests
response = requests.get("https://api.example.com/data")
print("状态码:", response.status_code) # 200表示成功
print("响应内容:", response.text) # 文本形式内容
带URL参数:
python
params = {"key1": "value1", "key2": "value2"}
response = requests.get("https://api.example.com/data", params=params)
print("请求URL:", response.url) # 自动拼接参数:https://api.example.com/data?key1=value1&key2=value2
3. 发送POST请求
提交表单数据:
python
data = {"username": "user1", "password": "123456"}
response = requests.post("https://api.example.com/login", data=data)
print("响应JSON:", response.json()) # 自动解析JSON响应
发送JSON数据:
python
import json
data = {"name": "John", "age": 30}
response = requests.post("https://api.example.com/user", json=data)
# 等效于手动设置headers和序列化:
# headers = {"Content-Type": "application/json"}
# response = requests.post(url, data=json.dumps(data), headers=headers)
4. 设置请求头(Headers)
python
headers = {
"User-Agent": "MyApp/1.0",
"Authorization": "Bearer YOUR_TOKEN"
}
response = requests.get("https://api.example.com/protected", headers=headers)
5. 处理响应
检查请求是否成功:
python
if response.status_code == 200:
print("请求成功!")
else:
print(f"请求失败,状态码:{response.status_code}")
# 更简洁的方式(失败时抛出异常):
response.raise_for_status() # 状态码非200时抛出HTTPError
解析内容:
python
# 文本内容(自动猜测编码)
print(response.text)
# 手动指定编码(如遇到乱码)
response.encoding = "utf-8"
print(response.text)
# JSON内容(直接解析)
data = response.json()
print(data["key"])
6. 错误处理
捕获网络相关异常:
python
try:
response = requests.get("https://api.example.com", timeout=5)
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print("HTTP错误:", errh)
except requests.exceptions.ConnectionError as errc:
print("连接错误:", errc)
except requests.exceptions.Timeout as errt:
print("超时错误:", errt)
except requests.exceptions.RequestException as err:
print("请求异常:", err)
7. 高级用法
使用会话(Session)保持状态:
python
with requests.Session() as session:
# 登录后保持cookies
session.post("https://api.example.com/login", data={"user": "admin", "pass": "secret"})
# 后续请求自动携带cookies
response = session.get("https://api.example.com/dashboard")
设置代理:
python
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
requests.get("http://example.com", proxies=proxies)
超时设置:
python
# 请求在3秒连接超时,5秒读取超时
response = requests.get("http://example.com", timeout=(3, 5))
禁用SSL验证(仅测试环境):
python
response = requests.get("https://api.example.com", verify=False)
8. 其他HTTP方法
python
# PUT请求
requests.put("https://api.example.com/item/1", data={"name": "new_name"})
# DELETE请求
requests.delete("https://api.example.com/item/1")
# HEAD请求(仅获取头部信息)
response = requests.head("https://api.example.com")
print(response.headers)
总结
- 使用
requests.get()
和requests.post()
处理常见请求。 - 通过
params
传递URL参数,data
或json
提交数据。 - 设置
headers
添加自定义请求头。 - 使用
response.json()
快速解析JSON响应。 - 通过
try-except
处理网络错误,raise_for_status()
检查HTTP状态码。 - 高级功能包括会话管理、代理、超时和SSL配置。