【问题标题】:Add Webelement text into list by iterating each element using for loop通过使用 for 循环迭代每个元素,将 Webelement 文本添加到列表中
【发布时间】:2021-11-24 19:03:53
【问题描述】:

有 5 个 Web 元素共享相同的 xpath。我想从每个元素中获取文本并将其存储在列表中。以下是我失败的尝试:

List<WebElement> ActualAdFormats_Elements = driver.findElements(By.xpath("(//h4[text()='Select Ad Format']/..//strong)"));
for(WebElement AdFormat:ActualAdFormats_Elements) {
    ActualAdFormat_List.add(AdFormat.getText());
        }

【问题讨论】:

  • 它是如何失败的?你的代码的结果是什么?
  • 结果如何?
  • ActualAdFormat_List 为 null 是我得到的。我以错误的方式定义它。按照 Cruise 提到的方式定义它并且它有效。谢谢!

标签: list selenium for-loop arraylist


【解决方案1】:

不确定您的代码中的 ActualAdFormat_List 是什么。

另外,xpath 中不需要括号,也可以删除它们。

请像这样定义list of string

List<String> ActualAdFormat_List = new ArrayList<String>();

并像这样使用它:

List<WebElement> ActualAdFormats_Elements = driver.findElements(By.xpath("//h4[text()='Select Ad Format']/..//strong"));
for(WebElement AdFormat : ActualAdFormats_Elements) {
    ActualAdFormat_List.add(AdFormat.getText());
        }

确保,

//h4[text()='Select Ad Format']/..//strong

代表HTMLDOM中的所有5个网络元素。

检查步骤:

Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 用@ 得到高亮 987654332@匹配节点。

【讨论】:

  • 我以错误的方式定义字符串列表,因此它为空。按照你提到的方式定义它。现在工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 2020-08-12
  • 2011-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多