高级陈旧元素

Advanced Stale elements

我一直在阅读陈旧的元素,但仍然有点困惑。例如,以下将不起作用,对吗?

 public void clickFoo(WebElement ele) {
    try {
      ele.click();
    } catch (StaleElementReferenceException ex) {
      ele.click();
    }
 }

因为如果 ele 陈旧,它将保持陈旧。最好的办法是重做 driver.findElement(By),但是正如您在此示例中所见,没有 xpath。您可以尝试 ele.getAttribute("id") 并使用它,但如果元素没有 id,这也将不起作用。所有调用它的方法都必须将 try/catch 放在它周围,这可能不可行。

是否有其他方法可以重新找到该元素?另外,假设有一个 id,在元素过时后 id 会保持不变吗?一旦过时,WebElement 对象 ele 中有什么不同?

(Java 日蚀)

我建议您不要创建上述方法。无需在 .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