代码之家  ›  专栏  ›  技术社区  ›  AnOldSoul

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

  •  0
  • AnOldSoul  · 技术社区  · 8 年前

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

    在那里,当我输入凭证并按登录时,一个临时的URL myNewUrl/oauthcheck?code=dsfdsfs3242343242423 显示一个代码(我需要提取),然后重定向到我的应用程序的主页(mynewurl)。我需要从这个临时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中提取“代码”?任何帮助都将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  1
  •   dangi13    8 年前

    如果您正在寻找任何想法,那么它可能是使用Selenium的Ajax拦截器或在控制台中捕获网络选项卡日志。 您可以使用某种用于Ajax截取的javascript代码来获取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);
    

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