如何使用 xpath 来确定我们选择的是哪个子元素?

例如,如果我们有一个如下的 xml:


<tr>

 <th>LION</th>

 <th>TIGER</th>

 <th>CHEETAH</th>

 <th>GIRAFFE</th>

 <th>BEAR</th>

</tr>

我想为 GIRAFFE 选择 xpath 元素......(使用 xpath)我如何能够分辨 GIRAFFE 元素下的哪个元素?显然,通过查看 xml,它是 //tr/th[4] .... 但是有没有办法可以使用 xpath 来确定它是 4th 下的元素?


潇湘沐
浏览 87回答 2
2回答

慕姐4208626

不完全确定您在问什么,但也许这些 XPath 之一会有所帮助......这个 XPath 表达式,count(/tr/th[.="GIRAFFE"]/preceding-sibling::th)+1将评估为4表示 GIRAFFEth元素是第 4 个th兄弟元素。这个 XPath,/tr/th[.="GIRAFFE"]将根据其内容选择 GIRAFFE&nbsp;th。这个 XPath,/tr/th[.="CHEETAH"]/following-sibling::th[1]将th凭借其在猎豹之后的地位选择长颈鹿th。

繁花如伊

如果您想通过行中的标题文本选择列元素并在 Selenium 中使用它,这里有一些示例:HTML 示例:<table>&nbsp; &nbsp; <thead>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>LION</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>TIGER</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>CHEETAH</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>GIRAFFE</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>BEAR</th>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; </thead>&nbsp; &nbsp; <tbody>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>1</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>2</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>3</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>4</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>5</td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>1</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>2</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>3</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>4</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>5</td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; </tbody></table>用于 Selenium 的 XPATH://table/tbody/tr/td[count(//table//th[.="GIRAFFE"]/preceding::th)+1]Selenium Java 使用示例:String animalName = "GIRAFFE";WebElement element = driver.findElement(By.xpath("//table/tbody/tr/td[count(//table//th[.='" + animalName + "']/preceding::th)+1]"));WebElement animalElementFromRow1 = driver.findElement(By.xpath("//table/tbody/tr[1]/td[count(//table//th[.='" + animalName + "']/preceding::th)+1]"));WebElement animalElementFromRow2 = driver.findElement(By.xpath("//table/tbody/tr[2]/td[count(//table//th[.='" + animalName + "']/preceding::th)+1]"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java