java - 如何让 Selenium 等待页面加载然后检查 URL?

标签 java selenium

我见过this question ,它是 wait + findElementBy 的组合。 但是,我的问题略有不同,因为我需要在页面完全加载后检查 URL(而不是元素)。

我已经尝试了以下解决方案,但它对我不起作用:

public void checkCurrentURL(String expectedURL) {
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // 5 seconds delay to load the page
    String realURL = driver.getCurrentUrl();
    System.out.println("------------------------------------URL is: "+realURL);
    Assert.assertTrue(realURL.equals(expectedURL));

}

这是我的 Selenium 版本:

       <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>
<小时/>

更新: 感谢@Guy,当我使用以下方法时:

public void checkCurrentURL(String expectedURL) {

        new WebDriverWait(driver, 2).until(
                new ExpectedCondition<Boolean>() {
                    @Override
                    public Boolean apply(WebDriver d) {
                        return d.executeScript("return document.readyState").equals("complete");
                    }   
                }
            );

        String realURL = driver.getCurrentUrl();
        System.out.println("------------------------------------URL is: "+realURL);
        Assert.assertTrue(realURL.equals(expectedURL));

    }

它提示:

The method until(Function<WebDriver,T>) in the type WebDriverWait is not applicable for the arguments ()

这里是the repository .

我将 Selenium 更新为 3.14.03.142.6对我不起作用。

最佳答案

implicitlyWait 用于配置搜索WebElement时的最大查找时间,这里不相关,以后会影响driver,不仅仅在方法范围内。

您可以使用WebDriverWait并检查document.readyState

new WebDriverWait(driver, pageLoadTimeout).until(
    new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver d) {
            return d.executeScript("return document.readyState").equals("complete");
        }   
    }
);

顺便说一句,3.4.0 版本已经相当老了(~2.5 岁)。考虑更新到版本 3.142.6(最新的非 alpha 版本)。

关于java - 如何让 Selenium 等待页面加载然后检查 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59443603/

相关文章:

java - 如何在 selenium webdriver 中的同一页面上加载新数据后定位页面的元素

javascript - Selenium JavaScript 与 Mocha beforeEach 为每个测试创建新的浏览器实例

java - StringTemplate 设置列表中最后一项的格式

java - 如何使用loopj概念在android中以Json格式发送本地主机服务器上的当前纬度和经度数据?

java - 我看不到 Swing JSeparator

python - 在 Selenium 中使用 find_element_by_class_name 遍历多个类

java - 需要 http 407 代理身份验证 : how to handle in java code

java - 是 :gen-class is the only way to extend Java class in Clojure?

python - python selenium 驱动程序中的 "Message: unknown error: cannot focus element"

vba - 禁用图像 - Selenium VBA Chromedriver