如何使用 Selenium 获得在路由到另一个 url 之前临时出现的重定向 url?

How to get a redirection url that appears temporarily before routing to another url using Selenium?

我有这个 url 我正在用它来获取代码。然后,我需要使用此代码并获取令牌。当我访问此 url mysite.com/oauth/authorize?response_type=code&client_id=ewrtergdgdfg324324242&redirect_uri=myNewUrl/oauth-check 时,我被定向到登录页面。

在那里,当我输入凭据并按登录时,会出现一个带有代码(我需要提取)的临时 url myNewUrl/oauthcheck?code=dsfdsfs3242343242423,然后重定向到我的应用程序的主页 (myNewUrl)。我需要从这个临时 url 中提取 "code"。但是这个 url 只是出现和消失。我尝试了以下代码来获取此代码。当我尝试 getCurrentUrl 时,我只获得了新主页 url。不是这个临时的 url。

System.setProperty("webdriver.chrome.driver",
                "/Users/me/Documents/chromedriver");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("headless");
        options.addArguments("window-size=1200x600");
        WebDriver driver = new ChromeDriver(options);
        driver.get("mysite.com/oauth/authorize?response_type=code&client_id=ewrtergdgdfg324324242&redirect_uri=https://myNewUrl/oauth-check");

        ((ChromeDriver) driver).findElementById("login_email").sendKeys("myuser@mysite.com");
        ((ChromeDriver) driver).findElementById("login_password").sendKeys("password");
        ((ChromeDriver) driver).findElementByXPath("//*[contains(@class, 'btn btn--primary btn--regular login-btn')]").click();

        String url = driver.getCurrentUrl();

如何从这个临时 url 中提取 "code"?任何帮助将不胜感激。

如果您正在寻找任何想法,那么它可能是一些 ajax 使用 selenium 的拦截器或在控制台中捕获网络选项卡日志。 也许您可以使用某种 javascript 代码来获取您的 URL 以进行 ajax 拦截,或者通过使用以下代码获取网络选项卡日志来获取它:

System.setProperty("webdriver.chrome.driver",
                   "D://ECLIPSE-WORKSPACE//Selenium-Demo//src//main//resources//drivers//chromedriver-2.35.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        WebDriver driver = new ChromeDriver(capabilities);
        driver.get("http://www.google.com");
        String scriptToExecute = "var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;";
        String netData = ((JavascriptExecutor)driver).executeScript(scriptToExecute).toString();
        System.out.println(netData);

我不确定它是否对您有帮助,但我的方法仅是这样。 希望对你有帮助。