python requests最全使用指南
Python的requests库是一个非常强大的工具,它允许你发送HTTP请求并获取服务器的响应。以下是requests库的一些常见用法:
- 发送GET请求
import requests
response = requests.get('https://api.github.com/some/endpoint')
print(response.json())
- 发送POST请求
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.github.com/some/endpoint', data=payload)
print(response.json())
- 发送带有参数的GET请求
import requests
params = {'param1': 'value1', 'param2': 'value2'}
response = requests.get('https://api.github.com/some/endpoint', params=params)
print(response.json())
- 发送JSON数据的POST请求
import requests
import json
data = json.dumps({'key1': 'value1', 'key2': 'value2'})
headers = {'Content-Type': 'application/json'}
response = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers)
print(response.json())
- 发送带有认证的请求
import requests
response = requests.get('https://api.github.com/some/endpoint', auth=('user', 'pass'))
print(response.json())
- 使用会话对象
import requests
s = requests.Session()
s.auth = ('user', 'pass')
r = s.get('https://api.github.com/some/endpoint')
print(r.json())
- 处理请求和响应
import requests
response = requests.get('https://api.github.com/some/endpoint')
print(response.status_code) # 打印状态码
print(response.headers) # 打印响应头
print(response.url) # 打印请求的URL
print(response.history) # 打印重定向历史记录列表
- 处理cookies
import requests
response = requests.get('https://api.github.com/some/endpoint')
print(response.cookies)
- 超时和异常处理
import requests
try:
response = requests.get('https://api.github.com/some/endpoint', timeout=0.01)
except requests.exceptions.Timeout:
print('请求超时')
- 文件上传
import requests
files = {'file': open('report.xls', 'rb')}
response = requests.post('https://api.github.com/some/endpoint', files=files)
- 使用响应内容
import requests
response = requests.get('https://api.github.com/some/endpoint')
print(response.text) # 以文本格式打印内容
print(response.content) #
评论已关闭