【问题标题】:Python requests returns 200 instead of 301Python 请求返回 200 而不是 301
【发布时间】:2020-07-30 09:45:01
【问题描述】:

url = "https://www.avito.ma/fr/2_mars/sacs_et_accessoires/Ch%C3%A2les_en_Vrai_Soie_Chanel_avec_boite_38445885.htm"

try   
    r = requests.get(url,headers={'User-Agent': ua.random},timeout=timeout) # execute a timed website request
    if r.status_code > 299: # check for bad status
        r.raise_for_status() # if confirmed raise bad status
    else:
        print(r.status_code, url) # otherwise print status code and url
except Exception as e:
     print('\nThe following exception: {0}, \nhas been found found on the following post: "{1}".\n'.format(e,url))

预期状态 = 301 永久移动

您可以访问该页面或使用 url 检查http://www.redirect-checker.org/index.php 以获得正确的终端打印。

返回状态 = 200 OK

页面已被移动,它应该返回上面的301 Moved Permanently,但它返回 200。我阅读了请求文档并检查了所有参数(allow_redirects=False 等),但我不认为这是配置错误。

我对为什么请求看不到重定向感到困惑。

有什么想法吗?

提前谢谢你。

【问题讨论】:

  • 在您提出请求后 - r.urlr.history 会向您展示什么?
  • r.url == 200 https://www.avito.ma/fr/2_mars/sacs_et_accessoires/Ch%C3%A2les_en_Vrai_Soie_Chanel_avec_boite_38445885.htm, r.history The following exception: 503 Server Error: Service Unavailable: Back-end server is at capacity for url: https://www.avito.ma/fr/2_mars/sacs_et_accessoires/Ch%C3%A2les_en_Vrai_Soie_Chanel_avec_boite_38445885.htm, has been found found on the following post: "https://www.avito.ma/fr/2_mars/sacs_et_accessoires/Ch%C3%A2les_en_Vrai_Soie_Chanel_avec_boite_38445885.htm". --Return--.
  • 会不会是服务器配置的问题?
  • 我在ipdb 中重新创建了 r.history,并将结果粘贴到了上面。
  • 从代码本身打印 r.history 会返回:[<Response [301]>, <Response [301]>] 这应该是正确的状态代码。但我仍然无法理解 historystatus_code 有何不同?

标签: python python-requests


【解决方案1】:

Python Requests 模块默认具有 True 中的 allow_redirect 参数。我已经用 False 对其进行了测试,它给出了您正在寻找的 301 代码。

阅读您上面的评论后请注意:r.history 将每个 response_code 保存在您现在保存在 r.status_code 中的那个之前(仅当您将参数保留为 True 时)。

【讨论】:

  • 如问题所示,我在添加参数时尝试了allow_redirects=False,但请求似乎没有返回status_code,这很遗憾破坏了代码的逻辑。
  • @Densetsu_No 实际上它确实返回一个。正如您在此link 中看到的,即使添加了参数,我也能够检索到status code
  • 我刚刚在终端中使用与代码中完全相同的参数进行了尝试,并且确实返回了status_code,让我尝试了解为什么在启动示例时它不起作用通过终端。
  • @Densetsu_No 我尝试添加您拥有的参数:1- 带有用户代理的标头和 2- 超时,它也可以工作。也许是错字?
  • raise_for_status link 似乎有问题。
猜你喜欢
  • 2019-11-15
  • 1970-01-01
  • 2021-06-16
  • 2019-05-23
  • 2016-08-08
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
相关资源
最近更新 更多