首页 > 解决方案 > 如何使用不同的搜索创建元素的 Xpath ( cssSelector / tag / ClassName )

问题描述

我想使用不同的 cssSelector / tag / ClassName 找到一个元素,并且他们得到它的 xpath 值(更具体地说,我有一个网站,当一天发生变化时,其中一个类会改变它的类)这是我该怎么做意思是:

<tr>
<td> 1.1.2019 </td>
<td> 2.1.2019 </td>
<td class="active"> 3.1.2019 </td>
<td> 4.1.2019 </td>
</tr>
<tr>
<td> </td>
<td> 10 </td>
<td> </td> #Here
<td> </td>
</tr>

我想根据那个“活动类”在哪里,点击它下面的表格。知道怎么做吗?

我想要的简短版本:

使用 cssSelector 查找元素

获取此元素的 Xpath <- 问题

使用编辑的 xpath 单击它

我想 GET XPATH OF LOCATED ELEMENT ,而不是使用 Xpath 定位它

标签: javaseleniumselenium-webdriverxpathselenium-chromedriver

解决方案


您可以通过定位<td>第一行中的所有元素并检查其中一个具有索引来找到索引

List<WebElement> columns = driver.findElements(By.xpath("//tr[td[@class='active']]/td")); # just an example, can be any other locator
int index = 0;
for (int i = 0 ; i < columns.getSize() ; i++) {
    String attribute = columns.get(i).getAttribute("class")
    if (attribute != null && attribute.equals("active")) {
        index = i + 1;
    }
}

推荐阅读