如何找到以 class 名称定位的网页元素的 xpath | Java 硒

How to find the xpath of element of a web page that located by it's class name | Java selenuim

我在一个网页上有一个 table,它的 xpath 有时会不同,但它的 class 名称不会。所以我可以通过它的 class 名称来处理它,但是我的代码需要该元素的 xpath 那么如何获取该元素的 xpath? 如何处理xpath不时变化的元素?

    String xpath = "here sould be the xpath of that element";
    wait_page_loading(By.xpath(table_xpath)); //this other function in my class wait the page loading
    WebElement Webtable = driver.findElement(By.xpath(table_xpath));
    List<WebElement> totalRowCount = Webtable.findElements(By.xpath(table_xpath + "/tbody/tr"));
    if(totalRowCount.size() <= 1) {
        throw new Exception("Can't find results in the problem page");
    }
    return totalRowCount.get(0).findElements(By.xpath("td")).get(6).getText();

非常感谢。

我看到一个 div 然后我们有一个 child table,请使用下面的 xpath :

//div[@class='table-responsive']/table

下面xPathreturnstable.

的所有行值
//div[@class='table-responsive']/table/tbody/tr

how to deal with such elements that its xpath differs from time to time?

如果 xPath 值是部分动态的,我建议您使用我们的 contains 方法。例如,

<input class = "User1235">

在上面 xPath 中,值 1235 是动态的,在这种情况下,您可以使用 contains

创建一个 xPath
//input[contains(@class,'User')]