Selenium - 定位具有相同类名的多个元素

标签 selenium

您好,我正在尝试查找具有相同 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/

相关文章:

python - selenium.common.exceptions.WebDriverException : Message: Failed to convert data to an object while trying to click an element with Selenium and Python

java - 使用 selenium webdriver 的 Amazon 登录和注销场景

jquery - 如何使用 Selenium IDE 测试 jQuery UI slider 小部件?

javascript - 如何使用 jquery 和 selenium 在 `shadow-root` 处访问 'chrome://downloads' 下的元素?

php - Selenium 测试用例返回 Process finished with exit code 0

java - 以编程方式在网页上下载动态图像

c# - 使用 Selenium C# 获取 Youtube 标题

Python Selenium 不断检查页面源代码中的短语

ruby-on-rails - Fixtures 和 Selenium and Rails(天哪?)

python - 如何让 Python 中的 Selenium WebDriver 休眠几毫秒