requests库的使用方法
时间: 2023-10-24 18:20:57 浏览: 60
1. 发送GET请求
```
import requests
response = requests.get('https://www.baidu.com/')
print(response.text)
```
2. 发送POST请求
```
import requests
data = {'username': 'admin', 'password': '123456'}
response = requests.post('https://www.example.com/login', data=data)
print(response.text)
```
3. 添加请求头
```
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.example.com/', headers=headers)
print(response.text)
```
4. 设置超时时间
```
import requests
response = requests.get('https://www.example.com/', timeout=3)
print(response.text)
```
5. 处理响应内容
```
import requests
response = requests.get('https://www.example.com/')
print(response.status_code)
print(response.headers)
print(response.cookies)
print(response.text)
```
6. 处理异常
```
import requests
try:
response = requests.get('https://www.example.com/')
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(e)
except requests.exceptions.Timeout as e:
print(e)
except requests.exceptions.RequestException as e:
print(e)
else:
print(response.text)
```
阅读全文