我建议您不要创建像上面这样的方法。无需在.click()
. 只需调用.click()
元素本身。
driver.findElement(By.id("test-id")).click();
或者
WebElement e = driver.findElement(By.id("test-id"));
e.click();
我经常使用的一种避免陈旧元素的方法是仅在需要时才找到元素,通常我通过页面对象方法来执行此操作。这是一个简单的例子。
主页的页面对象。
public class HomePage
{
private WebDriver driver;
public WebElement staleElement;
private By waitForLocator = By.id("sampleId");
// please put the variable declarations in alphabetical order
private By sampleElementLocator = By.id("sampleId");
public HomePage(WebDriver driver)
{
this.driver = driver;
// wait for page to finish loading
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(waitForLocator));
// see if we're on the right page
if (!driver.getCurrentUrl().contains("samplePage.jsp"))
{
throw new IllegalStateException("This is not the XXXX Sample page. Current URL: " + driver.getCurrentUrl());
}
}
public void clickSampleElement()
{
// sample method code goes here
driver.findElement(sampleElementLocator).click();
}
}
使用它
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.example.com");
HomePage homePage = new HomePage(driver);
homePage.clickSampleElement();
// do stuff that changes the page and makes the element stale
homePage.clickSampleElement();
现在我不再需要依赖旧的参考。我只是再次调用该方法,它为我完成了所有工作。
页面对象模型有很多参考资料。这是 Selenium wiki 中的一个。http://www.seleniumhq.org/docs/06_test_design_considerations.jsp#page-object-design-pattern
如果您想阅读有关什么是陈旧元素的更多信息,文档有很好的解释。http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp