通过使用 for 循环迭代每个元素,将 Webelement 文本添加到列表中
Add Webelement text into list by iterating each element using for loop
有 5 个网络元素共享相同的 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
是什么。
另外,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
正在 突出显示 与 1/1
匹配节点。
有 5 个网络元素共享相同的 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
是什么。
另外,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
.
检查步骤:
Press F12 in Chrome
-> 转到 element
部分 -> 执行 CTRL + F
-> 然后粘贴 xpath
并查看是否需要 element
正在 突出显示 与 1/1
匹配节点。