1

我一直在阅读有关陈旧元素的内容,但仍然有些困惑。例如,以下行不通,对吗?

 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 日食)

4

1 回答 1

2

我建议您不要创建像上面这样的方法。无需在.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

于 2016-07-19T18:08:09.900 回答