【问题标题】:Selenium - locating multiple elements with the same class nameSelenium - 定位具有相同类名的多个元素
【发布时间】:2015-10-04 04:58:38
【问题描述】:

您好,我正在尝试查找具有相同类名的多个元素。元素的类名和正文结构相同,但文字、链接和图片不同。

  <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());
            }

所以结果应该是从divs 中提取的 3 个不同标题的列表。 问题:结果是 3 个标题列表相同

AVG AntiVirus Free 2015
AVG AntiVirus Free 2015
AVG AntiVirus Free 2015

看起来我找到了 3 次相同的元素。有谁知道可能是什么问题?谢谢

【问题讨论】:

    标签: selenium


    【解决方案1】:

    如果div标签不包含id或者class,那么就这样使用

    List<WebElement> elements = driver.findElements(By.xpath("//div[contains(@style,'height:50px')]"));
    for(WebElement element : elements) {
       System.out.println(element.getText());
    }
    

    【讨论】:

      【解决方案2】:

      你也可以试试:-

      List<WebElement> list = driver.findElements(By.xpath(".//*[@class='dc-info']//a"));
          for(WebElement element : list) {
             System.out.println(element.getText());
          }
      

      【讨论】:

        【解决方案3】:
            List<WebElement> list = driver.findElements(By.xpath(".//*[@class='dc-item clearfix']//h2/a"));
            for(WebElement el : list) {
               System.out.println(el.getText());
            }
        

        【讨论】:

        • 谢谢,它会在子元素中写入所有可以找到的文本,(链接、描述、标题...)我只想访问 h2 标记。
        • 是的,我误读了这个问题。我已经更新了 xpath,新的可以吗?
        • 是的,它确实有效。谢谢你。但重点是.. 是否可以先保存整个子元素。 List list = driver.findElements(By.xpath("//div[@class='dc-item clearfix']"));然后访问它的不同部分。 list.get(1).findElement(By.xpath("//h2/a")).getText() 之类的东西。你知道这样的事情是否可能吗?
        • 啊好吧,明白了。我不知道,但我认为这是可能的。只有反复试验才能找到答案。
        • 这也是可能的。您必须从该 div 元素的子标签中提供 xpath。
        猜你喜欢
        • 2018-04-04
        • 1970-01-01
        • 1970-01-01
        • 2020-06-17
        • 2021-08-15
        • 1970-01-01
        • 2022-10-07
        • 1970-01-01
        • 2020-09-20
        相关资源
        最近更新 更多