【问题标题】:Python URL Gets Method returns status 200, even though it is 404Python URL Gets 方法返回状态 200,即使它是 404
【发布时间】:2017-04-22 01:23:00
【问题描述】:

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

import requests
answer = requests.get('http://www.website.com')
answer.status_code
>>>200

这给了我 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>'

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

谢谢!

【问题讨论】:

  • 您正在获取的网站可能正在返回状态 200,即使返回的内容包含文本 404 Not Found
  • 使用带有 -v 选项的 curl 等其他工具来获取所有标题和内容。确认标题不匹配。可能是 404 是在 php 代码中生成的,并且该代码没有正确设置状态代码

标签: python url request http-status-codes


【解决方案1】:

Requests Doc

重定向和历史 默认情况下,Requests 将对除 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]>]

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

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

>>> r.status_code
301

>>> r.history
[]

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

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

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

>>> r.history
[<Response [301]>]

【讨论】:

  • 这似乎是复制粘贴,这与他的问题有何关系。我们没有理由怀疑重定向是问题的一部分。如果您不这样做,那么您需要提出这种情况
猜你喜欢
  • 2015-03-16
  • 1970-01-01
  • 2016-02-10
  • 1970-01-01
  • 2013-08-14
  • 2017-07-29
  • 1970-01-01
  • 2016-07-28
  • 2022-12-25
相关资源
最近更新 更多