Java selenium xpath - 获取特定元素下的所有元素

时间:2014-12-23 09:28:35

标签: java selenium xpath

这是一个简化的HTML结构,我正在搜索:

<div class="main">
...other stuff...
       <td class="child">44</td>
       <td class="child">59</td>
       <td class="child">11</td>
</div>
<div class="main">
...other stuff...
       <td class="child">5</td>
       <td class="child">14</td>
       <td class="child">98</td>
</div>
...this kind of structure repeats with similar numbers a few more times but with identical class names

我需要提取第一个找到的主要课程下的所有数字,以便我查询搜索第一个主要数据,以及所有具有特定类别的数据。有人可以给我一个提示我做错了什么,因为这个查询给了我所有td&#39; child&#34;在所有&#34; main&#34; DIV&#39; S:

List<WebElement> koefi = driver.findElements(By.xpath("//div[@class='main'][1]//td[@class='child']"));

我做错了什么或者我的逻辑是对的,但是我错过了html的其他部分,因为结构太麻烦,我还没有粘贴在这里。

谢谢!!

P.S .: 我也尝试了这一点,但我再次获得了所有td&#34; child&#34;的内容。类,而不仅仅是第一个&#34; main&#34; ..

List<WebElement> koefi = driver.findElements(By.xpath("//*[1][@class='main']//td[@class='child']"));

更新 我设法通过首先出现&#34; main&#34;默认情况下由.findElement函数找到的div:

WebElement element = driver.findElement(By.xpath("//*[1][@id='main']"));

然后使用.findElements函数提取&#34; child&#34;类:

List<WebElement> kk = element.findElements(By.className("child"));

我仍然无法弄清楚为什么没有.findElements与我的xpath工作,或者它工作得太好,它提取每个&#34; main&#34;上课而不仅仅是第一个。原来的HTML太大了,不能粘贴在这里,所以我不想打扰你们!

2 个答案:

答案 0 :(得分:1)

更清晰的解决方案是首先使用类div抓取所有main,如下所示:

List<WebElement> allDivs = driver.findElements(By.className("main"));

然后,按照您的指定,找到包含td类的所有child,如下所示:

List<WebElement> tds = allDivs[0].findElements(By.className("child"));

之后,只需迭代所有“tds”并读出你的值。

答案 1 :(得分:0)

你在评论中说

  

“主要”不是直接的兄弟姐妹

所以我怀疑你违反了与XPath中//定义相关的常见错误。路径

//div[@class='main'][1]

选择文档中的第一个“main”div。原因是///descendant-or-self::node()/的简写(包括前导和尾部斜杠),所以这条路径的实际含义是

/descendant-or-self::node()/child::div[@class='main'][1]

当您看到它完全展开时,您会发现[1]child::步骤相关,而不是搜索后代,即您将获得文档中的所有div元素具有类“main”的类是它们各自父元素下的第一个div-with-class-main。如果你的实际HTML是

<div>
  <div class="main">...</div>
</div>
<div>
  <div class="main">...</div>
</div>
然后XPath会选择它们(它们都是父母的第一个)。如果您只想要文档中的第一个,那么您应该使用descendant::

/descendant::div[@class='main'][1]

只会给你第一个匹配的后代。