Python Requests 是一个简单易用的 HTTP 库,用于发送 HTTP 请求。它基于 urllib3
库,并且提供了比 urllib3
更易用的 API。
安装
要安装 Requests,你可以使用 pip:
pip install requests
发送 GET 请求
以下是一个发送 GET 请求的基本示例:
import requests
response = requests.get('https://api.github.com')
print(response.text)
发送 POST 请求
如果你需要发送 POST 请求,可以使用以下代码:
import requests
data = {'key': 'value'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.text)
响应内容
当发送请求后,你可以通过 response
对象来获取响应内容。以下是一些常用的属性:
response.status_code
:HTTP 状态码。response.headers
:响应头。response.text
:响应内容(文本格式)。response.json()
:响应内容(JSON 格式)。
请求头
你可以通过 headers
参数来设置请求头:
headers = {
'User-Agent': 'My User Agent 1.0',
'From': 'youremail@domain.com' # This is another valid field
}
response = requests.get('https://httpbin.org/get', headers=headers)
请求体
如果你需要发送请求体,可以使用 data
或 json
参数:
data = {'key': 'value'}
json_data = {'key': 'value'}
response = requests.post('https://httpbin.org/post', data=data)
response = requests.post('https://httpbin.org/post', json=json_data)
错误处理
当请求失败时,requests
会抛出异常。你可以捕获这些异常并处理它们:
try:
response = requests.get('https://httpbin.org/status/404')
except requests.exceptions.HTTPError as errh:
print("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
print("OOps: Something Else", err)
扩展阅读
想要了解更多关于 Python Requests 的信息,请访问我们的 Python Requests 教程。
[center]