Python Requests.head() 方法将 HTTP HEAD 请求发送到指定的 URL。HEAD 请求类似于 GET 请求,但它只检索标头,而不检索响应的正文。
这对于检查资源元数据(如大小或修改日期)非常有用,而无需下载整个内容。典型的使用案例包括检查资源是否存在或在决定发出完整的 GET 请求之前检索标头信息。
Requests.head() 的语法和可选参数类似于 requests.get() 的语法和可选参数,后者允许自定义标头、身份验证、超时等。
语法
以下是 Python Requests.head() 方法的语法和参数 -
参数
此函数不采用任何参数。
返回值
此方法返回响应对象。
示例 1
以下是基本示例,它向指定的 URL 发送一个简单的 HEAD 请求,并使用 python Requests.head() 方法打印状态代码和标头 -
输出
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'}
{'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 参数 -
输出
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'}
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 请求时如何处理错误的示例 -
输出
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'}