【问题标题】:How to handle catch and handle redirect loops through requests.get or selenium?如何通过 requests.get 或 selenium 处理捕获和处理重定向循环?
【发布时间】:2015-04-05 01:59:53
【问题描述】:

我正在尝试以编程方式确定某些网址的最终登录页面,但遇到了http://event.four33.co.kr/20131030/redirect.html,它基本上是循环回到自身:

<script type="text/javascript">
    var agent = navigator.userAgent;
    var redirectUrl = "";

    if (agent.indexOf("Windows NT") != -1)
    {
        redirectUrl = "https://play.google.com/store/apps/details?id=com.ftt.suhoji_gl_4kakao";
    }
    else if (agent.indexOf("iPhone") != -1)
    {
        redirectUrl = "https://itunes.apple.com/kr/app/id705181473?mt=8";
    }
    else if (agent.indexOf("iPad") != -1)
    {
        redirectUrl = "https://itunes.apple.com/kr/app//id705181473?mt=8";
    }
    else if (agent.indexOf("Android") != -1)
    {
        redirectUrl = "market://details?id=com.ftt.suhoji_gl_4kakao";
    }
    location.href = redirectUrl;
</script>

当我的脚本(见下面的 sn-p)命中它时,driver.current_url 永远不会返回。

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(1024, 768))
display.start()
driver=webdriver.Firefox()
driver.get('http://event.four33.co.kr/20131030/redirect.html')
driver.current_url

我尝试了 urllib2 和 requests,但没有找到方法让我抓住它,也没有阻止它。 有什么建议吗?

(请注意,由于重定向,此 url 实际上会查看访问它的代理。FireFox 和 Chrome 都没有被“捕获”,因此它会循环到自身。)

【问题讨论】:

    标签: python url selenium webdriver


    【解决方案1】:

    requests 可以处理:

    try:
        requests.get(looper)
    except requests.exceptions.TooManyRedirects:
        do stuff
    

    如果你想检测循环而不仅仅是中断,你可以使用类似于this one的代码:

    history = []
    while url not in history and len(history) < 42:
        history.append(url)
        r = requests.get(url, allow_redirects=False)
        if 'location' in r.headers:
            url = r.headers['location']
    

    【讨论】:

    • 谢谢格奥尔格。我刚刚尝试过,看起来 requests.get 没有意识到有多个重定向。我认为这是因为重定向是 javascript 驱动的?结果,没有抛出异常。
    • @user918081:是的,这些是 js 重定向,在服务器端你无能为力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多