org.openqa.selenium.
NoSuchElementException
问题
异常类:org.openqa.selenium.NoSuchElementException
解决方案
1、元素定位路径错误
修改定位路径,并先在浏览器中进行测试
2、页面(DOM)未加载完成
说明:如果你的元素定位路径中有些节点(元素节点、文本节点等)是通过JS生成的,当DOM加载完成时,JS可能还在执行,而selenium判断页面加载完成应该是不考虑JS的,所以可能会出现页面实际未全部加载完成的情况。
解决方法一
线程等待:如1000毫秒;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
解决方法二
显示等待:超时时间内,轮询查找,selenium2中默认轮询时间为500毫秒一次。
//示例代码:超时时间内轮询查找
//或者自己设置轮询时间:
//new WebDriverWait(driver, timeOutInSeconds, sleepInMillis);
WebElement we = new WebDriverWait(driver, 3).until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("testid"));
}
});
//selenium2源码
//参见类:org.openqa.selenium.support.ui.FluentWait<T>
//参见方法:public <V> V until(Function<? super T, V> isTrue)
//以下为轮询时间设置,重点的三句代码
public static final Duration FIVE_HUNDRED_MILLIS = new Duration(500, MILLISECONDS);
private Duration interval = FIVE_HUNDRED_MILLIS;
sleeper.sleep(interval);
解决方法三
隐式等待:全局设置,针对所有元素,超时时间内轮询查找。
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
3、driver焦点不在元素所在frame
将WebDriver的焦点切换到元素所在Frame或IFrame。