Parent XPath in Selenium

Profile picture for user arilio666

In Selenium, an XPath expression can locate elements on a web page. The Parent XPath is an XPath expression that selects the parent of a specified element.

  • Here we can see from this HuntMCQ site we need to fetch texts of all the topics with their inner texts beneath them as well.
  • This can be done only by also fetching the parent "li."
  • Using the //parent::* or //parent::li can help us fetch the parent of an element from the child.
public static void main(String[] args) throws Exception {
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.huntmcq.com/search/node?keys=istqb");
        driver.manage().window().maximize();

        List<WebElement> parentEles = driver.findElements(By.xpath("//h3[@class='search-result__title']//parent::li"));

        for (WebElement parEle : parentEles) {

            String textsPar = parEle.getText();
            System.out.println(textsPar);

        }

    }

}
  • Here we took the locator isolated with the parent, and then using an advanced for loop, we got texts of all the topics.