1、requests的基本使用
时间: 2024-02-02 13:04:38 浏览: 38
requests是一个常用的第三方库,用于发送HTTP请求和处理响应。它提供了简洁而友好的API,使得发送HTTP请求变得简单快捷。以下是requests的基本使用方法:
1. 安装requests库:在命令行中使用pip安装requests库,可以执行以下命令:
```
pip install requests
```
2. 导入requests库:在Python脚本中导入requests库,可以使用以下代码:
```python
import requests
```
3. 发送GET请求:
使用requests库发送GET请求非常简单,只需要调用`requests.get(url)`函数即可,其中`url`是要请求的URL地址。例如:
```python
import requests
response = requests.get('http://www.example.com')
print(response.text) # 打印响应内容
print(response.status_code) # 打印响应状态码
```
4. 发送POST请求:
如果要发送POST请求,可以调用`requests.post(url, data)`函数,并传递要发送的数据作为`data`参数。例如:
```python
import requests
data = {'username': 'user123', 'password': 'pass123'}
response = requests.post('http://www.example.com/login', data=data)
print(response.text) # 打印响应内容
```
5. 设置请求头:
可以通过`headers`参数设置请求头信息,例如设置User-Agent、Referer等。示例如下:
```python
import requests
headers = {'User-Agent': 'Mozilla/5.0', 'Referer': 'http://www.example.com'}
response = requests.get('http://www.example.com', headers=headers)
```
6. 处理响应:
requests库的响应对象提供了许多属性和方法,用于获取响应的各种信息,如状态码、响应头、响应内容等。例如:
```python
import requests
response = requests.get('http://www.example.com')
print(response.status_code) # 打印响应状态码
print(response.headers) # 打印响应头
print(response.text) # 打印响应内容
```
以上是requests库的基本使用方法。你可以根据具体的需求,进一步探索requests库提供的更多功能和选项。如果有更多问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)