使用python获取http标头(获取405)

tom*_*mes 4 python http python-requests

我正在尝试在python中创建一个基本的链接检查器。

使用以下代码时:

def get_link_response_code(link_to_check):  
    resp = requests.get(link_to_check)
    return resp.status_code
Run Code Online (Sandbox Code Playgroud)

我总是得到正确的响应代码,但这需要花费大量时间。

但是,使用此代码时:(requests.get替换为request.head)

def get_link_response_code(link_to_check):  
    resp = requests.head(link_to_check)
    return resp.status_code
Run Code Online (Sandbox Code Playgroud)

它通常可以正常运行,而且速度很快,但有时会返回HTTP 405(对于未真正断开的链接)。

为什么会出现405(错误方法)错误?如何快速检查断开的链接?谢谢。

ale*_*cxe 5

根据该规范405意味着Method not allowed这意味着你不能使用HEAD这种特殊的资源

处理并get()在以下情况下使用:

def get_link_response_code(link_to_check):
    resp = requests.head(link_to_check)
    if resp.status_code == 405:
        resp = requests.get(link_to_check)
    return resp.status_code
Run Code Online (Sandbox Code Playgroud)

附带说明,您可能不需要进行其他操作,get()因为这405是一个“好”错误-资源存在,但不能使用HEAD。您还可以检查Allow响应头值,该值必须根据您的HEAD请求进行设置

允许实体标头字段列出了由Request-URI标识的资源所支持的方法集。该字段的目的是严格告知接收者与资源关联的有效方法。405(不允许的方法)响应中必须存在允许头域。