Python requests.get()详解:发送HTTP GET请求

requests.get()是Python requests库中的一个核心函数,用于向指定的URL发送HTTP GET请求并获取服务器响应。

基本用法

以下是使用requests.get()函数的基本示例:

import requests

# 指定URL
url = 'https://www.example.com'

# 发送GET请求
response = requests.get(url)

# 检查响应状态码
if response.status_code == 200:
    # 成功获取响应
    print('响应内容:', response.text)
else:
    print('请求失败:', response.status_code)

在这个例子中:

  1. 我们首先导入requests库。
  2. 然后,我们定义要访问的URL。
  3. 使用requests.get(url)发送GET请求。
  4. 通过检查response.status_code是否为200来判断请求是否成功。
  5. 如果请求成功,我们使用response.text获取响应内容。

处理响应

requests.get()函数返回一个Response对象,其中包含了服务器的响应信息,例如:

  • response.status_code: HTTP状态码 (例如,200表示成功,404表示未找到)
  • response.text: 响应内容 (通常是HTML,但也可能是JSON或其他格式)
  • response.headers: 响应头信息 (包含服务器信息、内容类型等)
  • response.json(): 如果响应内容是JSON格式,可以使用此方法将其解析为Python字典

传递参数

你可以传递额外的参数给requests.get()函数,例如:

  • params: 以字典形式传递URL查询参数
  • headers: 以字典形式传递请求头
  • timeout: 设置请求超时时间
# 示例:传递查询参数
params = {'q': 'python requests', 'page': 2}
response = requests.get('https://www.google.com/search', params=params)

# 示例:传递请求头
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://www.example.com', headers=headers)

处理异常

网络请求可能会出现异常,例如连接错误或超时。可以使用try-except块来处理这些异常:

import requests

try:
    response = requests.get('https://www.example.com', timeout=5)
    response.raise_for_status()  # 如果状态码不是200,则抛出异常
except requests.exceptions.RequestException as e:
    print('请求出错:', e)

总结

requests.get()函数是Python中发送HTTP GET请求的强大工具。通过学习本文,您应该能够使用requests.get()函数发送GET请求、处理响应、传递参数以及处理异常。

有关更多信息,请参阅 requests 库的官方文档: https://requests.readthedocs.io/

Python requests.get()详解:发送HTTP GET请求

原文地址: https://www.cveoy.top/t/topic/cfuF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录