【问题标题】:How to correctly setup redirection with Python Requests for some corner-cases如何在某些极端情况下使用 Python 请求正确设置重定向
【发布时间】:2017-04-01 09:34:26
【问题描述】:

考虑以下代码sn-p:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import requests
from requests import exceptions

try:
    url=sys.argv[1]
except IndexError:
    print('No URL provided.')
    sys.exit(1)

print('\n--- {}\n'.format(url))

try:
    s = requests.Session()
    r = s.get(url)
except exceptions.TooManyRedirects as t:
    print('ERROR: {}'.format(t))
    r = s.get(url, allow_redirects=False)

print('-----------------------------')
print(r.status_code)
print(r.headers)

代码将 URL 作为输入并尝试对其运行 GET 请求。 我使用会话对象来管理多个请求等的 Cookie。

现在我的问题是,我有几个 URL(主要是 Tumblr),它们将在无限重定向循环中运行并在 30 次尝试后中断。

示例:http://ansgar-skoda.tumblr.com/post/96703389502

当我使用浏览器或使用

请求此页面时
curl -v -L http://ansgar-skoda.tumblr.com/post/96703389502

重定向有效,我将收到正确的网页。 看来我没有正确设置它。在研究 Requests 文档时,我看到选项 allow_redirects 默认为 True。在这种情况下,用户代理似乎不会影响结果。

任何提示如何在这里进行? 提前致谢。

【问题讨论】:

  • 奇怪的是,这在 Python 2 中有效,但我在 Python 3 中看到了与您相同的问题 - 两者都有相同的请求包 (2.13.0)。
  • 太棒了。很好发现。我会将其传递给 Requests 的问题跟踪器。

标签: python redirect python-requests


【解决方案1】:

截至今天,这是 Requests 中的一个错误 https://github.com/kennethreitz/requests/issues/3949

【讨论】:

    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多