如何使用 Python 从 Selenium 的重定向链中获取中间 URL?

问题描述

我正在使用 Selenium 和 Python API 和 Firefox 来做一些自动的事情,这是我的问题:

I'm using Selenium with Python API and Firefox to do some automatic stuff, and here's my problem:

  1. 点击原始页面上的链接,比如说在页面 a.com
  2. 我被重定向到 b.com/some/path?arg=value
  3. 我马上又被重定向到最终地址 c.com

那么有没有办法使用 Selenium Python API 获取中间重定向 URL b.com/some/path?arg=value?我试过 driver.current_url 但是当浏览器在 b.com 上时,似乎浏览器仍在加载中,并且只有在最终地址 c 时才返回结果.com 已加载.

So is there a way to get the intermediate redirect URL b.com/some/path?arg=value with Selenium Python API? I tried driver.current_url but when the browser is on b.com, seems the browser is still under loading and the result returned only if the final address c.com is loaded.

另一个问题是,有没有办法将一些事件处理程序添加到 Selenium 以进行 URL 更改?Phantomjs 有能力,但我不确定 Selenium.

Another question is that is there a way to add some event handlers to Selenium for like URL-change? Phantomjs has the capacity but I'm not sure for Selenium.


解决方案

回答我自己的问题.

如果重定向链很长,可以考虑尝试@alecxe 和@Krishnan 提供的方法.但在这种特定情况下,我发现了一个更简单的解决方法:

If the redirect chain is very long, consider to try the methods @alecxe and @Krishnan provided. But in this specific case, I've found a much easier workaround:

当页面最终登陆 c.com 时,使用driver.execute_script('return window.document.referrer') 获取中间网址

When the page finally landed c.com, use driver.execute_script('return window.document.referrer') to get the intermediate URL

相关文章