首页 > 解决方案 > 如何在 Selenium webdriver 中获取对象的通用 xpath

问题描述

String str = "some value" ;

getTestBase().getDriver().findElement(By.xpath("//h2[.='" + str + "']//parent::div//div[@id='sectionList'][1]/section/div/button")).click();

我需要将上述内容放入循环中,以便 [1] 每次都不断增加,如何更新上述整数的 xpath ?

标签: javaselenium-webdriverxpath

解决方案


String str = "some value" ;
WebDriver driver = getTestBase().getDriver();
for(int i=0; i<5; i++){
    driver.findElement(By.xpath("//h2[.='" + str 
    +"']//parent::div//div[@id='sectionList']["+i+"]/section/div/button")).click();
 }

这应该可以解决您的问题。5 只是我为编写解决方案假设的任意限制。

另一方面,您可以尝试获取所有元素并将元素存储在列表中。然后解析列表以获取按钮并单击它们。

就像是:

String str = "some value" ;
WebDriver driver = getTestBase().getDriver();
List<WebElement> listOfButtons = driver.findElements(By.xpath("//h2[.='" + str + "']//parent::div//div[@id='sectionList']//section/div/button""));
for(WebElement el: listOfButtons){
    el.click();
}
 

推荐阅读