我想得到一个元素的内容。在声明获取内容之前,我已经实现了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 : 带睡眠()的代码:
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如果我也使用隐式等待,我就不会得到这个值。建议不要使用睡眠()。使用显式等待始终是最佳实践。为什么我不使用显式等待获取元素的内容?
发布于 2019-05-28 07:42:42
相关的HTML可以帮助我们更好地调试这个问题。但是,由于所需的文本包含$字符,因此更好的方法是诱导WebDriverWait,以便检查给定文本是否存在于元素中,并且您可以使用以下任何一种解决方案:
textToBePresentInElementLocated:
20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("xpath"),“$”(System.out.println).getAttribute(“文本内容”);textToBePresentInElementValue:
20).until(ExpectedConditions.textToBePresentInElementValue(By.xpath("xpath"),“$”(System.out.println).getAttribute(“文本内容”);发布于 2019-05-28 07:04:21
你的错误是什么?该元素似乎没有正确加载。可能有一些动画正在进行,如弹出模式关闭,表加载等。通常,如果你知道这类动画需要多长时间的话,睡觉是可以的。
您也可以尝试流畅等待,但如果有动画正在进行,您可能仍然会遇到异常,例如驱动程序无法单击元素。
FluentWait:
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(timeout))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);发布于 2019-05-28 07:40:22
你能试一下吗:
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);https://stackoverflow.com/questions/56336418
复制相似问题