使用PageFactory时如何使用StaleElementReferenceException

时间:2016-07-26 17:35:30

标签: selenium selenium-webdriver

我们使用@FindBy注释来定义页面对象,如:

@FindBy(name="foo")
WebElement fooElement;

每当我调用此对象fooElement时,需要尝试使用上面的name=foo进行识别,对吗?

那我为什么会得到StaleElementReferenceException

如何克服这个问题?

每当我看到StaleElement时,我不想再次在这里(页面工厂除外)再次采用另一种方法:

WebElement fooElement=driver.findElement(By.name("foo"))

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

它为我工作..

#!/usr/bin/python
def test(arg1):
    y = arg1 * arg1
    print 'Inside the function', y
    return  y

y = test(6)
print 'Outside the function', y

答案 1 :(得分:-1)

异常StaleElementReferenceException表示找到的元素不再出现在页面中。它通常在目标元素位于页面更改之前和之后使用时附加。 以下是演示此问题的示例:

// trigger the update of the page
driver.findElement(By.name("foo1")).click();

// at this step the page is not yet updated, so the located element is not from the updated page.
WebElement element = driver.findElement(By.name("foo2"));

// at this step, the page is updated, the element is now deleted
element.click(); // throws `StaleElementReferenceException`

要解决此问题,您可以等待前一个元素过时:

fooElement1.click();

new WebDriverWait(driver, 10)
    .until(ExpectedConditions.stalenessOf(fooElement1));

fooElement2.click();

您还可以等待新元素变为可见:

new WebDriverWait(driver, 10)
    .until(ExpectedConditions.visibilityOf(fooElement3));

fooElement2.click();

最重要的是你需要等待一个特定的状态,这可能是异步更新的结果。

请注意,一种简单的方法是重试,这将再次定位元素并提供新的引用。但是我不推荐它,因为命令可以在更新之前执行:

try {
    fooElement.click();
} catch (StaleElementReferenceException ex) {
    fooElement.click();
}
相关问题