【问题标题】:How to follow 30x redirections using python requests.head method如何使用 python requests.head 方法遵循 30x 重定向
【发布时间】:2019-07-08 22:11:21
【问题描述】:

我正在使用 python 请求库向网站发送请求,我只对获取响应标头感兴趣。我遇到的问题是,如果我使用 requests.head() 方法,并且如果响应是 30x 重定向,则 requests.head() 方法将不会跟随重定向到最终网站。虽然使用 requests.get() 方法确实遵循重定向,但它比 requests.head() 慢得多。

这是一个例子:

>>> r = requests.head('http://google.com')
>>> r.status_code
301

>>> r = requests.get('http://google.com')
>>> r.status_code
200

因为 google.com 会将所有 http 请求重定向到 https,如果我将请求发送到 http://google.com,我将收到重定向到 https://google.com 的响应。

所以我的问题是,是否有办法(无需查看响应标头并手动跟随“位置”标头)让 requests.head() 方法跟随重定向?

我进行了多次搜索,但没有找到真正相关的内容。

【问题讨论】:

    标签: python http python-requests


    【解决方案1】:

    这就是你需要的!检查ref

    >>> import requests
    >>> r = requests.head('http://github.com/', allow_redirects=True)
    >>> r.history
    >>> [<Response [301]>]
    

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2015-03-01
      • 2017-07-17
      • 2014-02-25
      • 2015-06-07
      相关资源
      最近更新 更多