报错org.openqa.selenium.NoSuchElementException的原因有很多:
1、通过class或者name等定位元素,元素不唯一
2、元素位于iframe中
3、元素还未加载出来
第一种情况,建议使用id
或者xpath
来定位元素。
By.xpath("//input[@value='']");
第二种情况,需要获取iframe
区域
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
第三种情况,需要等待元素加载,可以设置固定延时时间
Thread.sleep(3000);
或者加入通用延时加载方法count
为最大等待次数,每次等待50毫秒
WebElement moveElemet = waitWebElement(driver, By.className("name"), 100);
// 延时加载
private static WebElement waitWebElement(WebDriver driver, By by, int count) throws Exception {
WebElement webElement = null;
boolean isWait = false;
for (int k = 0; k < count; k++) {
try {
webElement = driver.findElement(by);
if (isWait)
System.out.println(" ok!");
return webElement;
} catch (org.openqa.selenium.NoSuchElementException ex) {
isWait = true;
if (k == 0)
System.out.print("waitWebElement(" + by.toString() + ")");
else
System.out.print(".");
Thread.sleep(50);
}
}
if (isWait)
System.out.println(" outTime!");
return null;
}
作者:香芋味的猫丶