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

shi*_*zhz 4 python selenium redirect event-handling selenium-webdriver

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

  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时才返回结果。

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

Too*_*kit 5

您可以从performance日志中获取重定向。根据文档github 的回答,这里是我在 C# 中所做的,应该可以在 Python 中移植:

var options = new ChromeOptions();
var cap = DesiredCapabilities.Chrome();
var perfLogPrefs = new ChromePerformanceLoggingPreferences();
perfLogPrefs.AddTracingCategories(new string[] { "devtools.network" });
options.PerformanceLoggingPreferences = perfLogPrefs;
options.AddAdditionalCapability(CapabilityType.EnableProfiling, true, true);
options.SetLoggingPreference("performance", LogLevel.All);
var driver = new ChromeDriver(options);
var url = "https://some-website-that-will-redirect.com/";
driver.Navigate().GoToUrl(url);
var logs = driver.Manage().Logs.GetLog("performance"); //all your logs with redirects will be here
Run Code Online (Sandbox Code Playgroud)

循环通过logs,如果message.params.redirectResponse.url等于原始 URLmessage.params.request.url则将包含重定向 URL


shi*_*zhz 2

回答我自己的问题。

如果重定向链很长,请考虑尝试@alecxe和@Krishnan提供的方法。但在这种具体情况下,我找到了一个更简单的解决方法:

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