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

时间:2018-07-23 12:31:33

标签: java selenium automation selenium-chromedriver web-testing

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

当我输入凭据并按登录时,会出现一个临时URL myNewUrl/oauthcheck?code=dsfdsfs3242343242423,其中包含代码(需要提取),然后将其重定向到应用程序的主页(myNewUrl)。我需要从此临时URL中提取“代码”。但是这个URL只是出现而消失。我尝试下面的代码来获取此代码。当我尝试使用getCurrentUrl时,我只会得到新的主页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中提取“代码”?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果您正在寻找任何想法,则可能是一些使用硒的ajax拦截器或在控制台中捕获网络选项卡日志。 也许您可以使用某种JavaScript代码进行Ajax拦截来获取URL,也可以使用以下代码获取网络标签日志来获取URL:

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);

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