gpt4 book ai didi

java - 高级陈旧元素

转载 作者:行者123 更新时间:2023-12-01 09:40:54 25 4
gpt4 key购买 nike

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

 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 Eclipse)

最佳答案

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

关于java - 高级陈旧元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com