Search code examples
javaselenium-webdriverxpath

Searching forwards from found class in xpath


I'm currently using full xpath to find an element in Java\Selenium. The element has no id, so I only have div's and class to go on, here is my code.

driver.findElement(By.xpath("/html/body/root/app-root/div/div[2]/resource-utilisation/div/div[2]/div[2]/div[2]/div[2]/utilisation-input/div/div[2]/div/div/div[1]/div/ng-select")).getText()

Is there a way to find a class after another class you have found?

E.g., something like,

driver.findElements(By.xpath("//*[@class='resource-utilisation']//*[@class='utilisation-input']//*[@class='ng-select']"))

Solution

  • Yes, you can start searches from already found elements. A simple example would be.

    WebElement e = driver.findElement(By.xpath("//table"));
    e.findElement(By.xpath("./tr"));
                            ^ note this period is required
    

    NOTE: You must add a period to the start of the XPath of any chained .findElement() call.