【问题标题】:WebDriver - How to make the webdriver to wait until text displayed (without using locator)WebDriver - 如何让 webdriver 等到文本显示(不使用定位器)
【发布时间】:2015-07-23 06:53:12
【问题描述】:

我对@9​​87654321@ 执行了一个操作(比如说,我点击了一个按钮),结果是一个文本将显示在页面上。

我们不知道文本的定位元素,但我们知道将显示什么文本。

请提出一种等待文本显示的方法。

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

【问题讨论】:

    标签: java selenium webdriver


    【解决方案1】:

    进行基于 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));
    

    【讨论】:

    • 嗨 Saifur,从您的示例中如何检测文本是否在 10 秒后未显示
    • 10s 内找不到会抛出 NoSuchElement 异常。你是这个意思吗?
    【解决方案2】:

    即使您不知道确切的元素,也可以使用 WebDriverWait。如果预期文本在页面上仅出现 1 次,您可以通过 Xpath 访问它,如下所示:

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

    【讨论】:

    • 如果我们告诉 Web 驱动程序等待条件满足,为什么需要指定秒数?
    【解决方案3】:

    等待文本在元素中显示:

    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));
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2013-11-18
      • 2015-02-12
      • 2018-04-08
      • 1970-01-01
      相关资源
      最近更新 更多