requests中文手册
时间: 2023-06-11 21:06:22 浏览: 193
requests是一个Python库,用于发送HTTP请求。它是用Python语言编写的,简单易用,功能强大。以下是requests库的中文手册。
安装requests库:
```
pip install requests
```
发送HTTP GET请求:
```
import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
```
发送HTTP POST请求:
```
import requests
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://httpbin.org/post', data=data)
print(response.text)
```
发送HTTP PUT请求:
```
import requests
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.put('http://httpbin.org/put', data=data)
print(response.text)
```
发送HTTP DELETE请求:
```
import requests
response = requests.delete('http://httpbin.org/delete')
print(response.text)
```
设置请求头:
```
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.36'}
response = requests.get('http://httpbin.org/get', headers=headers)
print(response.text)
```
设置请求超时时间:
```
import requests
response = requests.get('http://httpbin.org/get', timeout=5)
print(response.text)
```
设置代理:
```
import requests
proxies = {'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080'}
response = requests.get('http://httpbin.org/get', proxies=proxies)
print(response.text)
```
设置认证:
```
import requests
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth('username', 'password')
response = requests.get('http://httpbin.org/get', auth=auth)
print(response.text)
```
发送JSON数据:
```
import requests
import json
data = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://httpbin.org/post', data=json.dumps(data), headers=headers)
print(response.text)
```
上传文件:
```
import requests
files = {'file': open('example.txt', 'rb')}
response = requests.post('http://httpbin.org/post', files=files)
print(response.text)
```
设置cookies:
```
import requests
cookies = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('http://httpbin.org/get', cookies=cookies)
print(response.text)
```
处理异常:
```
import requests
try:
response = requests.get('http://httpbin.org/get', timeout=0.1)
except requests.exceptions.Timeout as e:
print('Timeout error:', e)
except requests.exceptions.HTTPError as e:
print('HTTP error:', e)
except requests.exceptions.RequestException as e:
print('Other error:', e)
else:
print(response.text)
```
以上就是requests库的中文手册。更多详细的API文档可以参考官方文档:https://requests.readthedocs.io/en/latest/
阅读全文