Skip to content

Requests - 处理 GET 请求

本章重点介绍 HTTP GET 请求,它是用于从指定资源检索数据的最常用方法之一。requests 库使得发送 GET 请求变得简单直接。

要发送 GET 请求,可以使用 requests.get() 函数,并将要获取资源的 URL 作为参数传入。

import requests
import json # For pretty printing JSON
url = 'https://jsonplaceholder.typicode.com/users/1' # API endpoint for a single user
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
# Accessing response data
print(f"Status Code: {response.status_code}")
print(f"Content-Type Header: {response.headers['Content-Type']}")
# For JSON responses, use response.json()
user_data = response.json()
print("\nUser Data (parsed JSON):")
# Pretty print the JSON data
print(json.dumps(user_data, indent=2))
# For text content (like HTML or plain text), use response.text
# print(f"\nRaw Text Content (first 100 chars): {response.text[:100]}...")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as err:
print(f"Other error occurred: {err}")
Status Code: 200
Content-Type Header: application/json; charset=utf-8
User Data (parsed JSON):
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}

响应对象的关键要点: response.status_code:HTTP 状态码(例如,200 表示 OK,404 表示未找到)。 response.headers:响应头的字典状对象。 response.json():将 JSON 响应内容解析为 Python 字典或列表。如果解析失败,则引发 JSONDecodeError。 response.text:响应内容作为 Unicode 字符串。 response.content:响应内容作为字节(适用于图像或其他二进制文件)。

您可以使用 params 参数向 GET 请求传递 URL 参数(也称为查询字符串)。提供一个键值对字典,requests 将会正确编码并将其附加到 URL 中。

import requests
import json
url = 'https://jsonplaceholder.typicode.com/posts'
params = {
'userId': 1, # Filter posts for userId = 1
'_limit': 2 # Limit results to 2 posts (some APIs support this)
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
print(f"Request URL: {response.url}") # Shows the full URL with parameters
posts_data = response.json()
print("\nFiltered Posts Data:")
print(json.dumps(posts_data, indent=2))
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as err:
print(f"Other error occurred: {err}")

params 字典 {'userId': 1, '_limit': 2} 将被转换为查询字符串 ?userId=1&_limit=2 并附加到基础 URL 中。

Request URL: https://jsonplaceholder.typicode.com/posts?userId=1&_limit=2
Filtered Posts Data:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]

GET 请求是以下场景的基础:

  • 获取网页(HTML 内容)。
  • 调用 RESTful API 检索数据(通常是 JSON 或 XML 格式)。
  • 检查 Web 资源的可用性或状态。
  • 下载由 URL 标识的完整资源的文件。