Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用selenium获取当前URL 你好_Url_Selenium_Junit - Fatal编程技术网

使用selenium获取当前URL 你好

使用selenium获取当前URL 你好,url,selenium,junit,Url,Selenium,Junit,我想在点击链接后获得页面的当前url。当我单击(第一页的)链接时,该链接会打开一个新页面(第二页),我想获取第二页的url,但当我调用GetCurrentUrl()时,该方法返回第一页的url 这是我的代码: String att = driver.findElement(By.linkText("Lien 2")).getAttribute("href"); driver.findElement(By.linkText("Lien 2")).click(); // Open a the 2nd

我想在点击链接后获得页面的当前url。当我单击(第一页的)链接时,该链接会打开一个新页面(第二页),我想获取第二页的url,但当我调用GetCurrentUrl()时,该方法返回第一页的url

这是我的代码:

String att = driver.findElement(By.linkText("Lien 2")).getAttribute("href");
driver.findElement(By.linkText("Lien 2")).click(); // Open a the 2nd page
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
String act = driver.getCurrentUrl(); // Return the url of the 1rst page; but I want the 2nd
System.out.println("act "+act+" att "+att);
assertEquals(act, att);

非常感谢你的帮助

不要更改为
pageloadTimeout()
,而是尝试手动等待Url更改(这就是我在代码中所做的,所以我想我会回答)

  • 在代码中插入下面的函数定义
  • 该函数在循环中打印当前URL,以便有助于调试任何问题
  • 如果需要更长的超时时间,请在
    WebDriverWait(driver,30))
    中更改值“30”
确保按如下方式调用该函数:

try {
    waitForUrl(the-url-you-want-to-wait-for);
} catch (Exception ex) {
//handle exception
}
功能:

/**
 * Wait until the current page's URL changes to whatever you specify.
 * @param Url The URL you want to wait for.
 */
protected static void waitForUrl(WebDriver driver, final String Url) throws Exception {
    try {
        (new WebDriverWait(driver, 30)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                                    System.out.println(d.getCurrentUrl());
                return d.getCurrentUrl().toLowerCase().endsWith(Url);
            }
        });
    }
    catch (TimeoutException e) {
        throw new Exception("Timeout Exception encountered while waiting for URL " + Url + ": \n" + e.getMessage());
    }   
}
/**
*等待当前页面的URL更改为您指定的内容。
*@param Url您要等待的Url。
*/
受保护的静态void waitForUrl(WebDriver驱动程序,最终字符串Url)引发异常{
试一试{
(新的WebDriverWait(驱动程序,30))。直到(新的ExpectedCondition(){
公共布尔应用(WebDriver d){
System.out.println(d.getCurrentUrl());
返回d.getCurrentUrl().toLowerCase().endsWith(Url);
}
});
}
捕获(超时异常e){
抛出新异常(“等待URL“+URL+”:\n“+e.getMessage()”时遇到超时异常);
}   
}

当你说“打开第二页”时,你的意思是它会打开第二个窗口/选项卡吗?是的,在我的浏览器中打开第二个选项卡。你能提高我的声誉吗?因为没有10个声誉我无法回答?