安装 requests 模块
首先,你需要安装 requests 模块。你可以使用以下命令在你的 Python 环境中安装:
pip install requests
发送 GET 请求
import requests
url = 'https://www.example.com'
response = requests.get(url)
print(response.text) # 打印响应内容
print(response.status_code) # 打印状态码
发送 POST 请求
import requests
url = 'https://www.example.com'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.text)
添加请求头
import requests
url = 'https://www.example.com'
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
print(response.text)
处理响应
response 对象包含了所有与请求相关的信息:
import requests
url = 'https://www.example.com'
response = requests.get(url)
print(response.status_code) # 状态码
print(response.headers) # 响应头
print(response.text) # 响应内容
print(response.json()) # 将 JSON 格式的响应内容解析为 Python 对象
处理异常
import requests
url = 'https://www.example.com'
try:
response = requests.get(url)
response.raise_for_status() # 如果请求不成功,抛出异常
print(response.text)
except requests.exceptions.HTTPError as errh:
print(f"HTTP Error: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
print(f"Other Error: {err}")
这只是 requests 模块的一小部分功能。它还提供了许多其他功能,如文件上传、Session 管理、cookie 操作等。你可以查阅 requests 官方文档以获取更详细的信息:[requests 官方文档](https://docs.python-requests.org/en/latest/)。
转载请注明出处:http://www.pingtaimeng.com/article/detail/250/Python3