在某些情况下,我知道元素不会显示。但等待~30秒。
如何减少硒中NoSuchElementException
的等待时间?
示例代码:
String name;
try {
name = driver.findElement(By.xpath("XPath")).getText();
} catch (NoSuchElementException e) {
name = "Name not displayed";
}
答案 0 :(得分:1)
使用WebDriverWait
减少等待时间(等待5秒):
(new WebDriverWait(driver, 5)).until(ExpectedConditions.visibilityOf(name));
答案 1 :(得分:1)
我认为你正在寻找为你的司机设置不明智的等待时间:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
对于可以使用的简单案例,对于更高级的自动化,我会将其更改为显式等待(使用WebDriverWait
)。
有关等待的更多信息: http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
答案 2 :(得分:0)
我们可以使用显式等待这种情况,但必须小心使用的预期条件。
WebDriverWait wait=new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
有时,visibilityOf(Name)不起作用,因为大多数webelement名称的查找需要使用findElement语句。
WebElement name = driver.findElement(Locator);
如果元素不存在,此步骤可能会失败!