在Python中,requests
库是一个非常流行的HTTP库,用于发送各种HTTP请求。它简单易用,并且支持多种HTTP方法,如GET、POST、PUT、DELETE等。下面是如何使用requests
库来发送HTTP请求的基本步骤:
安装requests库
首先,确保你已经安装了requests
库。如果还没有安装,可以通过pip安装:
pip install requests
发送GET请求
GET请求通常用于请求数据。以下是一个发送GET请求的示例:
import requests
url = 'https://api.example.com/data'
response = requests.get(url)
# 检查响应状态码
print(response.status_code)
# 获取响应内容
print(response.text)
# 如果需要JSON格式的数据
data = response.json()
print(data)
发送POST请求
POST请求通常用于提交数据给服务器。以下是一个发送POST请求的示例,其中包含了JSON数据:
import requests
url = 'https://api.example.com/submit'
data = {'key': 'value'}
# 发送POST请求,数据以JSON格式发送
response = requests.post(url, json=data)
# 检查响应状态码
print(response.status_code)
# 获取响应内容
print(response.text)
如果你想发送表单数据(例如,在HTML表单中收集的数据),可以使用data
参数而不是json
参数:
# 发送POST请求,数据以表单格式发送
response = requests.post(url, data={'key': 'value'})
设置请求头
在发送请求时,你可能需要设置请求头(Headers)。以下是如何设置请求头的示例:
headers = {
'User-Agent': 'My App/1.0',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
response = requests.get(url, headers=headers)
设置请求参数
对于GET请求,有时你可能需要将参数附加到URL中。虽然你可以手动拼接URL,但requests
库允许你使用params
参数自动完成:
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get(url, params=params)
响应处理
除了获取文本响应(response.text
)和JSON响应(response.json()
)外,你还可以获取二进制响应(response.content
),这在处理图像、视频等文件时非常有用。
异常处理
当请求失败时(例如,网络问题、无效的URL、服务器错误等),requests
会抛出一个RequestException
异常。你可以通过try-except块来捕获这些异常:
try:
response = requests.get(url)
response.raise_for_status() # 如果响应状态码不是200,则抛出HTTPError异常
except requests.RequestException as e:
print(e)
这就是requests
库在Python中用于发送HTTP请求的基本方法。它提供了简单而强大的API来处理HTTP请求和响应。