如何获取具有相同属性的同一级别的元素或数据列表?

How can I get list of elements or data which are on same level with same attributes?

我有一个 Web 应用程序,它有一个 HTML 页面。

在这个页面结构是这样的:

<div class = 'abc'>
           <div class = 'pqr'>test1</div>
</div>
<div class = 'abc'>
           <div class = 'pqr'>-</div>
</div>
<div class = 'abc'>
           <div class = 'pqr'>-</div>
</div>
<div class = 'abc'>
           <div class = 'pqr'>test2</div>
</div>
<div class = 'abc'>
           <div class = 'pqr'>-</div>
</div>

这里我要从test1取数据到test2。

我已经尝试使用 [Node Number] 的 xpath 但我发现所有节点都在 [1] 级别。

有什么方法可以用“-”获取所有数据或元素列表 test1 到 test2 吗?

我以前见过这种问题

这里必须使用following-sibling

  • 首先我使用这种类型的 xpath :

    //div[text()='test1']/..//following-sibling::div[@class ='pqr' 而不是(包含(文本(),'test'))]

  • 那你需要改脚本了。 "Note : I have written code in JAVA"

    逻辑:

    while(找到的元素文本 = '-') { //这里获取数据 }

请试试这个方法。

我认为您不能将 Test1 和 Test2 元素用作标识符,因为它们与您要收集的节点位于同一行。否则,我认为您可以使用 findElements(by.Xpath("patern_to_search"))。这将 return 为您提供一组与您的模式匹配的元素。

猜想你想要下面的xpath :

(//div[@class='pqr'])[position()<=4]

注意 position() 谓词前的括号 ()

xpath tester中的输出:

Element='<div class="pqr">test1</div>'
Element='<div class="pqr">-</div>'
Element='<div class="pqr">-</div>'
Element='<div class="pqr">test2</div>'

另一种不使用 xpath 的方法:

   List<WebElement> element = driver.findElements(By.className("pqr"));     
   for(int i=0;i<element.size()-1;i++){
        System.out.println(element.get(i).getText());
   }