WebDriver-如何使WebDriver等到显示文本(不使用定位器)



我已经在WebDriver上执行了一个操作(例如,我单击了一个按钮),结果是文本将在页面上显示。

我们不知道文本的定位器元素,但是我们确实知道将显示哪些文本。

请建议一种等待文本显示的方法。

我遇到了WebDriverWait,但是它需要WebElement等待文本。

访问基于XPath文本的搜索。它允许您根据文本

找到一个元素
// with * we are doing tag indepenedent search. If you know the tag, say it's a `div`, then //div[contains(text(),'Text To find')] can be done
By byXpath = By.xpath("//*[contains(text(),'Text To find')]"); 
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(byXpath));

即使您不知道确切的元素,也可以使用WebDriverWait。如果预期文本在页面上只有1个出现,则可以通过这样的XPath到达:

WebDriverWait wait = new WebDriverWait(driver, numberOfSeconds);    
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'my text')]")));

以在元素中显示等待文本:

private ExpectedCondition elementTextDisplayed(WebElement element, String text) {
        return new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                return element.getText().equals(text);
            }
        };
    }
 protected void waitForElementTextDisplayed(WebElement element, String text) {
        wait.until(elementTextDisplayed(element, text));
    }

public void waitUntilTextToBePresentInElement(WebElement element, String text){
        wait.until(ExpectedConditions.textToBePresentInElement(element, text));
}

最新更新