Python - AI 助手

Python Requests head() 方法



Python Requests 的head()方法向指定的URL发送HTTP HEAD请求。HEAD请求类似于GET请求,但它只检索响应的头信息,而不检索响应的主体。

这对于检查资源元数据(例如大小或修改日期)非常有用,无需下载整个内容。典型的用例包括检查资源是否存在或在决定发出完整的GET请求之前检索头信息。

requests.head()的语法和可选参数类似于requests.get(),允许使用头信息、身份验证、超时等进行自定义。

语法

以下是Python Requests head()方法的语法和参数:

requests.head()

参数

此函数不接受任何参数。

返回值

此方法返回响应对象。

示例 1

以下是一个基本示例,它使用python requests head()方法向指定的URL发送简单的HEAD请求,并打印状态码和头信息:

import requests
response = requests.head('https://tutorialspoint.com/')
print(response.status_code)
print(response.headers) 

输出

403
{'Cache-Control': 'max-age=2592000', 'Content-Type': 'text/html; charset=iso-8859-1', 'Date': 'Mon, 24 Jun 2024 10:34:00 GMT', 'Expires': 'Wed, 24 Jul 2024 10:34:00 GMT', 'Server': 'Apache/2.4.59 (Ubuntu)', 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'SAMEORIGIN', 'X-Version': 'OCT-10 V1', 'Transfer-Encoding': 'chunked', 'Connection': 'close'}

示例 2

如果我们想使用Python中的requests模块发送带有参数的HEAD请求,我们可以使用params参数通过URL查询字符串传递参数。此示例在HEAD请求中包含URL参数:

import requests

# Define the URL
url = 'https://httpbin.org/headers'

# Define the parameters
params = {'param1': 'value1', 'param2': 'value2'}

# Send the HEAD request with parameters
response = requests.head(url, params=params)

# Print the response status code
print('Status Code:', response.status_code)

# Print the response headers
print('Response Headers:', response.headers)

输出

Status Code: 200
Response Headers: {'Date': 'Mon, 24 Jun 2024 10:39:18 GMT', 'Content-Type': 'application/json', 'Content-Length': '235', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}

示例 3

使用Python中的requests模块发送HEAD请求时,务必处理请求过程中可能发生的潜在错误。这是一个处理HEAD请求错误的示例:

import requests

# Define the URL
url = 'https://httpbin.org/headers'

# Define the parameters
params = {'param1': 'value1', 'param2': 'value2'}

try:
    # Send the HEAD request with parameters
    response = requests.head(url, params=params)

    # Check if the request was successful (status code 2xx)
    if response.ok:
        # Print the response headers
        print('Response Headers:', response.headers)
    else:
        # Print an error message with the status code
        print('Error:', response.status_code)

except requests.Timeout:
    # Handle timeout error
    print('Timeout Error: Request timed out.')

except requests.RequestException as e:
    # Handle other request exceptions
    print('Request Exception:', e)

输出

Response Headers: {'Date': 'Mon, 24 Jun 2024 10:42:30 GMT', 'Content-Type': 'application/json', 'Content-Length': '235', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}
python_modules.htm
广告 (guǎnggào)
© . All rights reserved.