首先,确保你已经安装了 requests 库:
pip install requests
以下是一些基本的用法:
1. 发送 GET 请求:
import requests
url = 'https://www.example.com'
response = requests.get(url)
print(response.status_code) # 打印响应状态码
print(response.text) # 打印响应文本
2. 发送 POST 请求:
import requests
url = 'https://www.example.com'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.status_code)
print(response.text)
3. 添加请求头:
import requests
url = 'https://www.example.com'
headers = {'User-Agent': 'my-app/0.0.1'}
response = requests.get(url, headers=headers)
print(response.status_code)
print(response.text)
4. 处理 JSON 响应:
import requests
url = 'https://api.example.com/data'
response = requests.get(url)
data = response.json() # 解析 JSON 响应
print(data)
5. 处理异常:
import requests
url = 'https://www.example.com'
try:
response = requests.get(url)
response.raise_for_status() # 如果请求不成功,抛出异常
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("Error:", err)
这只是 requests 库的一小部分功能。它提供了许多其他功能,如文件上传、cookie 处理、会话管理等。详细信息可以在 [官方文档](https://docs.python-requests.org/en/latest/) 中找到。
转载请注明出处:http://www.zyzy.cn/article/detail/13299/Python3