request库的基本操作
时间: 2024-06-09 19:05:36 浏览: 6
requests库是一个常用的Python第三方库,用于发送HTTP请求和处理响应内容。以下是requests库的基本操作:
1. 发送HTTP请求
可以使用requests库的get()、post()、put()、delete()等方法发送HTTP请求,其中最常用的是get()和post()方法。
示例:
```python
import requests
# 发送GET请求
response = requests.get('https://www.baidu.com/')
print(response.text)
# 发送POST请求
data = {'username': 'admin', 'password': '123456'}
response = requests.post('http://example.com/login', data=data)
print(response.text)
```
2. 设置请求头
可以使用headers参数来设置请求头,常见的请求头包括User-Agent、Referer、Cookie等。
示例:
```python
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get('https://www.baidu.com/', headers=headers)
print(response.text)
```
3. 传递参数
可以使用params参数来传递URL参数,示例:
```python
import requests
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('http://example.com/get', params=params)
print(response.url)
```
4. 发送文件
可以使用files参数来上传文件,示例:
```python
import requests
files = {'file': open('example.txt', 'rb')}
response = requests.post('http://example.com/upload', files=files)
print(response.text)
```
5. 处理响应
可以使用response对象的text、content、json()等方法来处理响应内容,示例:
```python
import requests
response = requests.get('https://www.baidu.com/')
print(response.text)
print(response.content)
print(response.json())
```
以上就是requests库的基本操作,还有很多高级用法可以参考官方文档。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.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)