requests------网络请求

85 阅读1分钟
  1. requests 是 Python 中一个非常流行和强大的库,用于发起 HTTP 请求。它简化了与网络交互的过程,使得发送请求和处理响应变得很简单。
  • 使用 pip 来安装 requests
pip install requests
  • 引入 requests
 import requests
  1. 常见用法:requests 库支持多种 HTTP 请求方法,包括 GET、POST、PUT、DELETE 等
  • 发起 GET 请求
response = requests.get('https://api.example.com/data')
print(response.status_code)  # 查看响应状态码
print(response.text)         # 查看响应内容(字符串形式)
  • 发起 POST 请求
data = {
    'key1': 'value1',
    'key2': 'value2'
}
response = requests.post('https://api.example.com/submit', data=data)
print(response.status_code)
print(response.json())       # 如果响应是 JSON 格式,解析为字典
  • 带参数的请求
params = {
    'param1': 'value1',
    'param2': 'value2'
}
response = requests.get('https://api.example.com/search', params=params)
print(response.url)  # 显示完整的请求 URL
  • 发送 JSON 数据
import json

data = {
    'name': 'Alice',
    'age': 30
}
response = requests.post('https://api.example.com/users', json=data)
print(response.json())
  • 设置请求头
### 有时你需要自定义请求头,比如设置内容类型或添加认证信息:
headers = {
    'User-Agent': 'my-app/0.0.1',
    'Authorization': 'Bearer your_token_here'
}
response = requests.get('https://api.example.com/protected', headers=headers)
print(response.text)
  • 处理文件上传
files = {'file': open('report.txt', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
print(response.text)
  • 错误处理
#### 处理异常情况非常重要。可以使用 response.raise_for_status() 来引发异常:
response = requests.get('https://api.example.com/data')
try:
    response.raise_for_status()  # 如果响应代码不是200,抛出异常
    data = response.json()
except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")
except Exception as err:
    print(f"Other error occurred: {err}")
  1. 示例代码:下面是一个完整的示例,展示如何使用 requests 发起 GET 和 POST 请求:
import requests

# 发送 GET 请求
def get_data():
    response = requests.get('https://jsonplaceholder.typicode.com/posts')
    if response.status_code == 200:
        print('获取到的数据:', response.json())
    else:
        print('请求失败,状态码:', response.status_code)

# 发送 POST 请求
def create_post():
    url = 'https://jsonplaceholder.typicode.com/posts'
    data = {
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
    }
    response = requests.post(url, json=data)
    if response.status_code == 201:
        print('创建的帖子:', response.json())
    else:
        print('请求失败,状态码:', response.status_code)

# 执行测试
get_data()
create_post()