在Selenium 2 / Java等待条件最干净的方法?

时间:2012-04-13 14:28:08

标签: java selenium webdriver selenium-webdriver

我正在尝试找到等待特定字符串出现在页面中的最干净的代码。我现在最好的是相当笨重的

new Wait() {
    @Override
    public boolean until() {
        return !webDriver.findElement(By.tagName("html"))
               .getText().contains("please choose another");
    }
}.wait("wait failed!", 60000);

有更优雅的方式吗?

3 个答案:

答案 0 :(得分:3)

如果这是你想要做的,那么

webDriver.findElement(By.xpath("//*[contains(text(),'please choose another')]"));
带有Implicit wait

对我来说似乎有点好(从“干净代码”的角度来看),因为它只是一行代码。

答案 1 :(得分:1)

您可以使用Webdriver的内置方法进行显式等待 - 请参阅examples here

请注意,如果可能,最好检查文本是否在特定元素中而不是在任何位置。检查它是否在任何地方都可能导致误报(即如果有人在页面上的其他位置添加相同的字符串,您将不再检查您认为的是什么)。

答案 2 :(得分:0)

创建WebDriverWait类对象

WebDriverWait wait = new WebDriverWait(driver, 500);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(text(),'please choose another']")));