如何使用Selenium和Java使用显式wait代替sleep()获取元素的内容?

问题描述 投票:2回答:3

我想获取一个元素的内容。我在获取内容的语句之前实现了一个显式的20秒的等待。但我无法获取内容。我可以得到元素的内容,如果我使用 sleep() 2秒。我试过的代码是

WebDriverWait wait1 = new WebDriverWait(driver,20);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath")));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is : 

使用sleep()的代码:

WebDriverWait wait1 = new WebDriverWait(driver,20);
Thread.sleep(2000);
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is : $0.00

如果我也使用隐式等待,我就得不到值了。建议不要使用sleep()。使用显式等待是最好的做法。为什么我使用显式等待没有得到元素的内容?

selenium selenium-webdriver webdriver sleep webdriverwait
3个回答
1
投票

相关的HTML可以帮助我们更好的调试这个问题。然而由于所需的文本中含有 $ 因此,更好的方法是诱导出 WebDriverWait 对于 期待检查给定文本是否存在于元素中。 你可以使用以下任何一种解决方案。

  • textToBePresentInElementLocated:

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("xpath"), "$")).getAttribute("text-content"));
    
  • textToBePresentInElementValue:

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementValue(By.xpath("xpath"), "$")).getAttribute("text-content"));
    

0
投票

你得到的错误是什么?好像是元素没有正常加载。可能有一些动画正在进行,比如弹出式模态关闭,表格加载等。通常情况下,如果你知道这些动画需要多长时间的话,放上sleeps是可以的。

你也可以试试fluentwait,但是如果有动画在进行,你可能还是会出现异常,比如驱动无法点击某个元素。

FluentWait。

Wait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(timeout))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class)
    .ignoring(StaleElementReferenceException.class);

0
投票

你能不能试一试。

Wait<WebDriver> wait = new FluentWait<WebDriver>((WebDriver) driver).withTimeout(20, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("XPath"))));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);
© www.soinside.com 2019 - 2024. All rights reserved.