您好,我正在尝试查找具有相同 className 的多个元素。元素的类名和主体结构相同,但文本、链接和图片不同。
<div class="dc-content-right clearfix"> (parent)
<div class="dc-item clearfix"> (child nodes)
<div class="dc-item clearfix">
<div class="dc-item clearfix">
每个子元素看起来都像这样:
<div class="dc-item clearfix">
<div class="dc-icon">
<div class="dc-info">
<h2>
<a href="http://www.avg.com/ww-en/free-antivirus-download">AVG AntiVirusFree 2015</a>
</h2>
每个子元素的 H2 标记中都有不同的文本。因此,一旦它是 AVG AntiVirus Free 2015,那么它就是 Internet Security.... 等等。所以我想做的是将所有元素保存到列表中,然后使用它们。 首先,我将这些元素保存到 WebElements 列表中:
List <"WebElement"> list = driver.findElements(By.xpath("//div[@class='dc-item clearfix']"));
之后我想遍历列表并为屏幕上的每个元素编写 h2 文本:
for(WebElement i:superDiv)
{
System.out.println(i.findElement(By.xpath("//h2/a")).getText());
}
因此结果应该是从 div
中提取的 3 个不同标题的列表。 问题:结果是 3 个相同标题的列表!
AVG AntiVirus Free 2015
AVG AntiVirus Free 2015
AVG AntiVirus Free 2015
看起来我找到了同一个元素 3 次。有谁知道可能是什么问题?谢谢
最佳答案
List<WebElement> list = driver.findElements(By.xpath(".//*[@class='dc-item clearfix']//h2/a"));
for(WebElement el : list) {
System.out.println(el.getText());
}
关于Selenium - 定位具有相同类名的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31425551/