python requests模块用法
时间: 2023-11-03 14:55:31 浏览: 97
python requests用法
requests是Python中一个常用的HTTP库,用于向Web服务器发送HTTP/1.1请求。
使用requests模块,可以方便地进行GET、POST等请求,并处理响应结果。
以下是requests模块的基本用法:
1. 安装requests模块:在命令行中输入 pip install requests。
2. 发送GET请求:
```python
import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.text)
```
3. 发送带参数的GET请求:
```python
import requests
url = 'http://www.example.com'
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get(url, params=params)
print(response.text)
```
4. 发送POST请求:
```python
import requests
url = 'http://www.example.com'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.text)
```
5. 发送带文件的POST请求:
```python
import requests
url = 'http://www.example.com'
files = {'file': open('example.txt', 'rb')}
response = requests.post(url, files=files)
print(response.text)
```
6. 发送带headers的请求:
```python
import requests
url = 'http://www.example.com'
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
print(response.text)
```
7. 处理异常:
```python
import requests
url = 'http://www.example.com'
try:
response = requests.get(url, timeout=1)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
```
以上就是requests模块的基本用法。更多高级用法可以查看官方文档:https://requests.readthedocs.io/en/latest/。
阅读全文