Home > Software design >  XPath - Select Elements at the first level ex: after Html tag all child tags
XPath - Select Elements at the first level ex: after Html tag all child tags

Time:10-19

So say I have a html structure like so

<!DOCTYPE HTML>
<html>
    <body><child></child></body>
    <div></div>
    <div><child></child></div>
    <script><child></child></script>
    <iframe></iframe>
    <div></div>
</html>

say I only wanted to get the children of the html tag and not the decendents of these children I would do something like:

webDriver.findElements(By.xpath("//html/*[not(*)]"))

and perhaps before I run that line I would wait for a full page load with a function like this:

public void waitForPageLoad() {

        Wait<WebDriver> wait = new WebDriverWait(webDriver, Duration.of(30, ChronoUnit.SECONDS));
        wait.until(new Function<WebDriver, Boolean>() {
            public Boolean apply(WebDriver driver) {
                System.out.println("Current Window State       : "
                      String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")));
                return String
                    .valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))
                    .equals("complete");
            }
        });
    }

When I run the above code however I only get the first div and the iframe tags and that is it. What could be the issue here? there is no shadow root elements at the top level only inside one of the body tags descendants. I have used different methods of waiting for page load like checking the hash of the page source then waiting for 30 seconds.

Any help would be great to find out what the problem is.

CodePudding user response:

The XPath expression you mention (//html/*[not(*)]) actually means: "find all the html elements in the document, and then find all their child elements, and then filter that set to include only those which don't have any child elements of their own).

If you just want to retrieve the child elements of the root html element, then the XPath you need is just /html/*

  • Related