【问题标题】:Webdriver stale element exception when element DOM didn't change元素 DOM 未更改时的 Webdriver 陈旧元素异常
【发布时间】:2013-11-18 03:32:35
【问题描述】:

我在 Java 中使用 WebDriver。

我想从下面的金额字段中获取所有金额值,所以我打算循环遍历每个表格行,并查找是否选中了复选框,将金额设置为定义的数字。

示例源代码可在此处找到: http://eric-lin.net/upload/index.php

我使用以下Java方法查找金额字段值:

public void fillInAllAmountForSelectedItems() {

    List<WebElement> allItems = driver
            .findElements(By
                    .xpath("//table[@id = 'bulkPaymentForm:itemTable']//tbody[@id = 'bulkPaymentForm:itemTable:tbody_element']//tr[contains(@class, 'handCursor row-border tranItemRow')]"));
    System.out.println(allItems.size());
    //return 3, expected

    waitTimer(2, 1000);

    for (WebElement item : allItems) {
        System.out.println(item.findElement(By.xpath("//td[4]"))
                .getAttribute("Value"));
    }       
}

大多数时候,foreach 循环会因为过时元素异常而失败。我不明白,因为 DOM 没有改变。

当它工作时,foreach 循环不打印任何内容,因此看起来它没有正确定位元素。

我该怎么做才能修复它,我需要做什么才能实现此功能的目的,为所有检查项目填写金额值?

非常感谢。

【问题讨论】:

  • 你试过添加wait()函数吗?如果您使用的是eclipse,请尝试逐步执行(调试模式)
  • 请注意,td 中的 input 字段将包含金额,而不是 td 本身。

标签: java selenium webdriver selenium-webdriver


【解决方案1】:

处理StaleElementException 通常是一个尝试重试直到成功的故事。 DOM 可能会因多种原因而刷新,从而导致元素过时。

在处理元素列表时有时使用且通常有效的策略是逐个获取每个项目。一个很好的解决方案发布在here,示例代码如下。

您将需要构造 xpath /css 选择器以相应地引用所需的表格单元格。请注意,该值将从 td 中的金额 input 字段中检索 - 如果您尝试从 td 获取文本,它将是空白的,就像您现在看到的那样。

//get the number of items that are required
int size = driver.findElements(By.cssSelector("table#mytable>tbody>tr>td[4]/input")).size();

//now work with each one individually, rather than with a list
for(int i = 1; i <= size; i++) {
    String locator = String.format("table#mytable>tbody>tr[%d]>td[4]/input", i);
    WebElement inputField = driver.findElement(By.cssSelector(locator));
    //get or set the value of the input element
    System.out.println(inputField.getAttribute("value"));
}

【讨论】:

  • 您好 Faiz,您的解决方案看起来不错,但我似乎无法通过 cssSelector 找到金额字段元素。我用付款表的 ID #bulkPaymentForm:itemTable 替换了 ID #mytable,它抱怨 org.openqa.selenium.WebDriverException: An invalid or illegal string was specified
  • 我使用 xpath //table[@id = 'bulkPaymentForm:itemTable']//tbody//tr[%d]/td[4]/input" 并且它有效,但我仍然想知道为什么 cssSelector 不起作用。谢谢
  • 表 id 中的 : 可能是导致 cssSelector 无法工作的罪魁祸首。 : 对 css 有特定的含义,用于指定伪类。请参阅第 6.6 节伪类here
  • 使用 xpath,您是否能够访问这些字段并摆脱 StaleElementException
  • 我能够使用 xpath 检索字段并摆脱 StaleElementException。您的整体解决方案对我来说非常好,非常感谢。
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 2017-12-16
相关资源
最近更新 更多