Python Requests 使用教程
简介
Python的requests
库是一个简单易用的HTTP请求库,它可以方便地发送HTTP请求和处理响应。本教程将介绍如何使用requests
库发送GET和POST请求,以及如何处理响应。
安装
首先,确保你已经安装了Python。然后,可以使用以下命令安装requests
库:
pip install requests
发送GET请求
使用requests
库发送GET请求非常简单。只需要调用requests.get()
方法,并传入URL作为参数即可。
import requests
response = requests.get('http://www.example.com')
上述代码将发送一个GET请求到http://www.example.com
,并将响应保存在response
变量中。
发送带参数的GET请求
如果需要发送带参数的GET请求,可以在URL中添加查询字符串参数。requests
库可以通过在get()
方法中传入params
参数来实现。
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('http://www.example.com', params=payload)
上述代码将发送一个带有查询字符串参数的GET请求到http://www.example.com
。
发送POST请求
使用requests
库发送POST请求也非常简单。只需要调用requests.post()
方法,并传入URL和请求体作为参数即可。
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://www.example.com', data=payload)
上述代码将发送一个POST请求到http://www.example.com
,并将请求体payload
作为参数。
处理响应
response
对象包含了服务器返回的所有信息。可以通过调用response.text
方法获取响应的内容。
import requests
response = requests.get('http://www.example.com')
print(response.text)
上述代码将打印出服务器返回的响应内容。
此外,response
对象还包含其他有用的属性和方法,例如response.status_code
可以获取响应的状态码,response.headers
可以获取响应的头部信息。
错误处理
在发送请求过程中,可能会遇到各种错误。requests
库提供了一些方法来处理这些错误。
import requests
try:
response = requests.get('http://www.example.com')
response.raise_for_status() # 如果响应状态码不是200,将抛出异常
except requests.exceptions.HTTPError as err:
print('HTTP Error:', err)
except requests.exceptions.RequestException as err:
print('Error:', err)
上述代码将捕获requests
库可能抛出的异常,并进行相应处理。
总结
本教程介绍了如何使用requests
库发送GET和POST请求,以及如何处理响应。requests
库非常强大且易用,适合用于各种HTTP请求场景。详细的使用方法可以参考requests
库的官方文档。