<think>我们正在详细讲解Python requests库的使用。根据用户提供的引用内容,requests库是一个用于发送HTTP请求的Python库,它简化了与Web服务的交互。我们将按照以下结构进行讲解:
1. **安装requests库**
2. **requests库的核心方法**
- HTTP请求方法(GET, POST, PUT, DELETE等)
- 通用方法:request()方法
3. **响应对象(Response)**
4. **请求参数详解**
- params参数(用于GET请求的查询字符串)
- 其他常用参数(headers, data, json, cookies等)
5. **处理响应内容**
6. **异常处理**
在讲解过程中,我们将结合引用内容,并适当添加代码示例和说明。
### 1. 安装requests库
安装requests库非常简单,可以通过pip命令进行安装。可以使用以下命令(可以选择国内镜像源加速安装):
```bash
pip install requests -i https://mirrors.aliyun.com/pypi/simple
```
安装完成后,就可以在Python中导入requests库了。
### 2. requests库的核心方法
requests库提供了多种方法来发送HTTP请求,最常用的有:
- `requests.get()`: 发送GET请求
- `requests.post()`: 发送POST请求
- `requests.put()`: 发送PUT请求
- `requests.delete()`: 发送DELETE请求
此外,还有一个通用的`requests.request()`方法,它可以通过指定method参数来发送任意类型的请求。例如:
```python
resp = requests.request('GET', url)
# 等价于
resp = requests.get(url)
```
#### GET请求示例
```python
import requests
url = 'http://httpbin.org/get'
params = {'key1': 'value1', 'key2': 'value2'} # 查询参数
response = requests.get(url, params=params)
print(response.url) # 查看实际请求的URL,包含查询参数
```
#### POST请求示例
POST请求通常用于提交表单数据或JSON数据。
```python
url = 'http://httpbin.org/post'
# 表单数据
data = {'key1': 'value1', 'key2': 'value2'}
# 或者JSON数据
json_data = {'key1': 'value1', 'key2': 'value2'}
# 发送表单数据
response = requests.post(url, data=data)
# 发送JSON数据
response = requests.post(url, json=json_data)
```
### 3. 响应对象(Response)
当我们发送一个请求后,会返回一个Response对象,它包含了服务器返回的所有信息。常用的属性和方法有:
- `response.status_code`: HTTP状态码(200表示成功,404表示未找到等)
- `response.text`: 响应内容的字符串形式(自动根据响应头部的字符集进行解码)
- `response.content`: 响应内容的二进制形式
- `response.json()`: 如果响应内容是JSON格式,则将其解析为字典或列表
- `response.headers`: 响应头(字典形式)
- `response.url`: 实际请求的URL(可能有重定向)
示例:
```python
response = requests.get('http://httpbin.org/get')
print(response.status_code) # 200
print(response.headers['Content-Type']) # 'application/json'
print(response.json()) # 解析JSON响应体
```
### 4. 请求参数详解
在发送请求时,我们可以传递多种参数来控制请求。
#### params参数(用于GET请求)
params参数是一个字典,用于在URL中添加查询字符串。例如:
```python
params = {'search': 'requests', 'page': 2}
response = requests.get('https://httpbin.org/get', params=params)
```
实际请求的URL将会是:`https://httpbin.org/get?search=requests&page=2`
#### data参数
data参数用于在POST请求中发送表单数据(即`application/x-www-form-urlencoded`类型)。也可以发送多部分编码文件(multipart/form-data),这时需要传递一个文件字典。
#### json参数
json参数用于发送JSON数据(即`application/json`类型)。requests会自动将字典转换为JSON字符串,并设置请求头中的`Content-Type`为`application/json`。
#### headers参数
headers参数是一个字典,用于设置HTTP请求头。例如设置User-Agent:
```python
headers = {'User-Agent': 'my-app/0.0.1'}
response = requests.get(url, headers=headers)
```
#### cookies参数
cookies参数用于设置请求的Cookie。可以传递一个字典,或者使用`requests.cookies.RequestsCookieJar`对象。
#### 其他参数
- `timeout`: 设置请求超时时间(秒)
- `allow_redirects`: 是否允许重定向(默认为True)
- `auth`: 用于HTTP认证
### 5. 处理响应内容
响应内容可以通过多种方式获取:
- 文本内容:`response.text`
- 二进制内容:`response.content`
- JSON内容:`response.json()`
注意:`response.json()`在响应内容不是JSON格式时会抛出异常。
### 6. 异常处理
requests库在遇到网络问题(如DNS查询失败、连接拒绝等)时会抛出异常。常见的异常有:
- `requests.exceptions.ConnectionError`: 网络连接错误
- `requests.exceptions.Timeout`: 请求超时
- `requests.exceptions.HTTPError`: HTTP错误(非200状态码,但通常我们需要自己检查状态码)
我们可以使用try-except块来处理异常:
```python
try:
response = requests.get('http://httpbin.org/get', timeout=5)
response.raise_for_status() # 如果状态码不是200,抛出HTTPError异常
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as err:
print(f"HTTP错误: {err}")
except requests.exceptions.RequestException as err:
print(f"请求错误: {err}")
```
### 总结
以上是requests库的基本使用教程。requests库提供了简洁的API,使得在Python中发送HTTP请求变得非常容易。通过掌握上述内容,你可以完成大多数HTTP请求任务。
§§相关问题§§
1. 如何在requests中设置代理?
2. 如何处理requests库中的重定向问题?
3. 使用requests库上传文件的方法是什么?
4. 如何通过requests库保持会话(Session)?
[^1]: 引用[1]:探索Python中的HTTP请求:使用requests库。
[^2]: 引用[2]:python基础之Requests库。
[^3]: 引用[3]:python的requests库全部教程_Python爬虫小白入门(二)requests库。
[^4]: 引用[4]:Python - requests库。
[^5]: 引用[5]:requests.get(url,params=None,**kwargs)。</think>### Python requests库使用教程及详细说明
requests库是Python中最流行的HTTP客户端库,它简化了HTTP请求的发送过程,支持多种HTTP方法,并提供了人性化的接口。以下是详细使用指南:
---
#### 1. **安装与导入**
```bash
# 使用阿里云镜像加速安装
pip install requests -i https://mirrors.aliyun.com/pypi/simple
```
```python
import requests # 导入库
```
---
#### 2. **核心HTTP方法**
##### GET请求 - 获取数据
```python
# 基本GET请求
response = requests.get("https://api.example.com/data")
# 带参数请求(自动构建URL)
params = {"key1": "value1", "key2": "value2"}
response = requests.get("https://api.example.com/search", params=params)
```
##### POST请求 - 提交数据
```python
# 表单数据提交
data = {"username": "admin", "password": "secret"}
response = requests.post("https://api.example.com/login", data=data)
# JSON数据提交(自动设置Content-Type)
json_data = {"name": "Alice", "age": 30}
response = requests.post("https://api.example.com/users", json=json_data)
```
##### 其他HTTP方法
```python
# PUT更新数据
requests.put("https://api.example.com/users/1", json={"age": 31})
# DELETE删除数据
requests.delete("https://api.example.com/users/1")
# PATCH部分更新(非幂等操作,慎用)
requests.patch("https://api.example.com/users/1", json={"age": 32})
```
---
#### 3. **响应处理**
```python
response = requests.get("https://api.example.com/data")
print(response.status_code) # HTTP状态码 (200, 404等)
print(response.text) # 文本响应内容
print(response.json()) # JSON响应解析为字典
print(response.headers) # 响应头信息
print(response.cookies) # 服务器返回的Cookies
print(response.url) # 最终请求URL(含重定向)
```
---
#### 4. **高级参数配置**
##### 请求头定制
```python
headers = {
"User-Agent": "MyApp/1.0",
"Authorization": "Bearer token123"
}
requests.get(url, headers=headers)
```
##### 超时控制
```python
# 设置3秒连接超时和5秒读取超时
requests.get(url, timeout=(3, 5))
```
##### 会话保持(Session)
```python
with requests.Session() as session:
session.get("https://api.example.com/login") # 保持cookies
session.post("https://api.example.com/data") # 使用相同会话
```
---
#### 5. **异常处理**
```python
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # 检查4xx/5xx错误
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as err:
print(f"HTTP错误: {err}")
except requests.exceptions.RequestException as err:
print(f"请求异常: {err}")
```
---
#### 6. **文件操作**
```python
# 文件下载
with open("image.jpg", "wb") as f:
f.write(requests.get("https://example.com/image.jpg").content)
# 文件上传
files = {"file": open("report.pdf", "rb")}
requests.post("https://api.example.com/upload", files=files)
```
---
#### 7. **代理与SSL验证**
```python
# 使用代理
proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.10:1080"}
requests.get(url, proxies=proxies)
# 禁用SSL验证(测试环境)
requests.get(url, verify=False)
```
---
### 最佳实践
1. **连接复用**:使用`Session`对象减少TCP连接开销
2. **响应编码**:手动设置`response.encoding = 'utf-8'`解决乱码
3. **流式传输**:大文件使用`stream=True`分块下载
4. **重试机制**:结合`urllib3.Retry`实现自动重试
```python
# 流式下载示例
with requests.get(url, stream=True) as r:
for chunk in r.iter_content(chunk_size=8192):
process_chunk(chunk)
```