Python URL Gets 方法返回状态 200,即使它是 404

Ale*_*ser 5 python url request http-status-codes

我使用以下代码返回 URL 的状态

import requests
answer = requests.get('http://www.website.com')
answer.status_code
>>>200
Run Code Online (Sandbox Code Playgroud)

这给了我 200。

但是,网站应该返回 404。

answer.content
>>>b'<html><head>\r\n<title>404 Not Found</title>\r\n</head><body>\r\n<h1>Not   Found</h1>\r\n<p>The requested URL index.php was not found on this server.</p>\r\n<hr>\r\n<address>Apache/2.2.22 (Linux) Server at Port <small onclick="document.getElementById(\'login\').style.display = \'block\';">80</small></address>\r\n</body></html><div id="login" style="display:none;"><pre align=center><form method=post>Password: <input type=password name=pass><input type=submit value=\'>>\'></form></pre></div>'
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我差异源自何处以及如何解决此问题以获得answer.status_code = 404 作为结果而不是 200?我无法直接访问服务器,但我可以询问管理员。

谢谢你!

宏杰李*_*宏杰李 2

请求文件

重定向和历史记录 默认情况下,请求将对除 HEAD 之外的所有动词执行位置重定向。

我们可以使用 Response 对象的历史属性来跟踪重定向。

Response.history 列表包含为完成请求而创建的 Response 对象。该列表按从最旧到最新的响应排序。

例如,GitHub 将所有 HTTP 请求重定向到 HTTPS:

>>> r = requests.get('http://github.com')

>>> r.url
'https://github.com/'

>>> r.status_code
200

>>> r.history
[<Response [301]>]
Run Code Online (Sandbox Code Playgroud)

如果您使用 GET、OPTIONS、POST、PUT、PATCH 或 DELETE,则可以使用allow_redirects参数禁用重定向处理:

>>> r = requests.get('http://github.com', allow_redirects=False)

>>> r.status_code
301

>>> r.history
[]
Run Code Online (Sandbox Code Playgroud)

如果您使用 HEAD,您也可以启用重定向:

>>> r = requests.head('http://github.com', allow_redirects=True)

>>> r.url
'https://github.com/'

>>> r.history
[<Response [301]>]
Run Code Online (Sandbox Code Playgroud)