首页 > 解决方案 > 在 selenium 中使用 Xpath 获取 TH 索引号

问题描述

嗨,我只想使用唯一的 Xpath获取 TH 列的索引号。Like A 循环将运行并检查哪个TH column Xpath匹配并返回索引号。有什么办法可以在 selenium 中做到这一点?直到现在我能够获取标签索引并运行循环,但现在我已经用 xpath 检查了每个 TH,而不是它是否匹配,并给了我索引号。请让我知道我是否可以通过这种逻辑或任何其他任何Xpath技术来实现这一目标。

Table = driver.findElement(By.xpath("//table/thead[@class='ui-datatable-thead']"))

List<WebElement> rows_head = Table.findElements(By.tagName('th'))

int head_size= rows_head.size()

System.out.println(head_size);

for (int c = 1; c <= head_size; c++) {
    driver.findElement(By.xpath(
       "//th[4][@class='ui-state-default ui-unselectable-text ui-sortable-column']")
    )
    // Here is something I want loop will check the each TH with above given
    // Xapth and return the TH index in the table on match TH xpath index.
}

标签: javaseleniumselenium-webdriverxpathhtml-table

解决方案


Selenium 不提供 API 来返回找到的元素的 xpath。所以你不能通过比较 xpath 来归档你的目标。

但是 Selenium 提供 API 来获取找到的元素的属性值,您可以与它进行比较以查看它是否是您想要的元素。

WebElement thead = driver.findElement(By.xpath("//table/thead[@class='ui-datatable-thead']"));

List<WebElement> heads = thead.findElements(By.tagName('th'));

int head_size= heads.size()

System.out.println(head_size);

String expectedClass = "ui-state-default ui-unselectable-text ui-sortable-column"

int i = 1;
for (; i <= head_size; i++) {

    if(heads[i].getAttribute("class").equal(expectedClass))
      // check attribute class value is as expect
      // you can change to other attribute or check more than one attribute 
      break;
    )
}

System.out.println("Matched th index: " + i);

推荐阅读