Python requests.get() 函数详解:发送 HTTP GET 请求
Python requests.get() 函数详解:发送 HTTP GET 请求
requests.get() 函数是 Python requests 库中用于发送 HTTP GET 请求的核心方法。它提供了一种简单且强大的方式与 Web 服务器进行交互,并获取所需数据。
基本用法
以下是使用 requests.get() 发送 GET 请求并处理响应的基本步骤:pythonimport requests
1. 发送 GET 请求url = 'http://example.com/api/data'response = requests.get(url)
2. 检查响应状态码if response.status_code == 200: # 请求成功 print('请求成功') # 3. 处理响应内容 # 根据响应类型,选择合适的方法解析 data = response.json() # 如果是 JSON 数据 # data = response.text # 如果是纯文本数据 print(data)
else: # 请求失败 print(f'请求失败: 状态码 {response.status_code}')
代码解释:
- 导入
requests库: 首先,我们需要导入requests库才能使用其中的函数。2. 发送 GET 请求: 使用requests.get(url)发送 GET 请求到指定的 URL。3. 检查响应状态码: 使用response.status_code属性检查请求是否成功。200状态码表示请求成功。4. 处理响应内容: -response.json(): 如果响应内容是 JSON 格式,可以使用此方法将其解析为 Python 字典或列表。 -response.text: 如果响应内容是纯文本,可以使用此属性获取。
传递参数
requests.get() 函数允许传递额外的参数来自定义请求,例如:
- 查询参数: 使用
params参数传递字典形式的查询字符串。* 请求头: 使用headers参数传递字典形式的请求头信息。python# 查询参数示例params = {'key1': 'value1', 'key2': 'value2'}response = requests.get('http://example.com/api/search', params=params)
请求头示例headers = {'User-Agent': 'Mozilla/5.0'}response = requests.get('http://example.com/api/data', headers=headers)
错误处理
除了检查状态码,还可以使用 try...except 块捕获潜在的网络错误:pythonimport requestsfrom requests.exceptions import RequestException
try: response = requests.get('http://example.com/api/data', timeout=5) response.raise_for_status() # 如果状态码不是 200,抛出异常except RequestException as e: print(f'请求出错: {e}')
总结
requests.get() 函数是 Python 中发送 HTTP GET 请求的强大工具。通过学习其基本用法、参数传递、错误处理等技巧,你可以轻松地与 Web 服务器交互并获取所需数据。
原文地址: https://www.cveoy.top/t/topic/cfb6 著作权归作者所有。请勿转载和采集!