我正在使用PageObject/PageFactory设计模式来实现UI自动化。使用Selenium 2.0 WebDriver,JAVA,我随机得到错误:org.openqa.Selenium.StaleElementReferenceException:元素不再附加到DOM,当我尝试这样的逻辑时:
@FindBy(how = HOW.ID, using = "item")
private List<WebElement> items
private void getItemThroughName(String name) {
wait(items);
for(int i = 0; i < items.size(); i++) {
try {
Thread.sleep(0500);
} catch (InterruptedException e) { }
this.wait(items);
if(items.get(i).getText().contains(name)) {
System.out.println("Found");
break;
}
}
}
错误随机发生在if语句行,正如你所看到的,我已经尝试了一些方法来避免这种情况,比如睡一小段时间,或者再次等待元素,两者都不能100%工作
首先,如果您的by上确实有多个ID为"item"的元素,您应该记录一个错误或与网站上的开发人员交谈以修复该错误。ID是唯一的。
正如对该问题的评论已经暗示的那样,在这种情况下,您应该使用ExplicitWait:
private void getItemThroughName(String name) {
new WebDriverWait(driver, 30)
.until(ExpectedConditions.presenceOfElementLocated(
By.xpath("id('item')[.='" + name + "']")
));
// A timeout exception will be thrown otherwise
System.out.println("Found");
}