[java] Webdriver findElements By xpath

1)I am doing a tutorial to show how findElements By xpath works. I would like to know why it returns all the texts that following the <div> element with attribute id=container.

code for xpath: By.xpath("//div[@id='container']

2) how should I modify the code so it just return first or first few nodes that follow the parent note e.g. first node like 'Home', first few node like, Home, Manual Testing and Automation Testing.

Thanks for your advise and help!

Here is the code fragment for this tutorial:

import java.util.List;

import org.junit.Test;
import org.junit.Before;
import org.junit.After;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WD_findElements 
{
    @Test
    public void test_byxpath(){

        WebDriver driver = new FirefoxDriver();

        try{
            driver.get("http://www.hexbytes.com");

        List<WebElement> elements = driver.findElements(By.xpath("//div[@id='container']"));    
            System.out.println("Test7 number of elements: " + elements.size());

            for(WebElement ele : elements){
                //ele.sendKeys("hexbyes");
                System.out.println(ele.getText());
                //System.out.println(ele.getAttribute("id"));
                //System.out.println(ele.getTagName());
            } 
        }
        finally {
            driver.close();
        }

    }//end of test_byxpath

 public void xpathDemo2() {
           WebDriver driver = new FirefoxDriver();
           try{
               driver.get("http://www.hexbytes.com");
               WebElement webelement = driver.findElement(By.id("container"));
               //matching single element with attribute value=container
               System.out.println("The id value is: " + webelement.getAttribute("id"));
               System.out.println("The tag name is: " + webelement.getTagName());
           }
           finally {
               driver.close();
           }
       }//end of xpathDemo2 

public void xpathDemo3() {
       WebDriver driver = new FirefoxDriver();
       try{
           driver.get("http://www.hexbytes.com");
          //find first child node of div element with attribute=container
          List<WebElement> elements = driver.findElements(By.xpath("//div[@id='container']/*[1]"));
          System.out.println("Test1 number of elements: " + elements.size()); 

          for(WebElement ele : elements){
              System.out.println(ele.getTagName());
              System.out.println(ele.getAttribute("id"));
              System.out.println("");
              System.out.println("");
          }
   }
   finally {
       driver.close();
   }
 }//end of xpathDemo3
 }

This question is related to java selenium xpath selenium-webdriver webdriver

The answer is


Your questions:

Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText() Where getText will return all text content of all children of your result.

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.

Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for. Example:

<p1> <div/> </p1 <p2/> 

The following to parent of the div is p2. This would be:

 //div[@id='container'][1]/parent::*/following-sibling::* 

or shorter

 //div[@id='container'][1]/../following-sibling::* 

If you are only looking for the first one extent the expression with an "predicate" (e.g [1] - for the first one. or [position() &lt; 4]for the first three)

If your are looking for the first child of the first div:

//div[@id='container'][1]/*[1]

If there is only one div with id an you are looking for the first child:

   //div[@id='container']/*[1]

and so on.


The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!


Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to xpath

Xpath: select div that contains class AND whose specific child element contains text XPath: difference between dot and text() How to set "value" to input web element using selenium? How to click a href link using Selenium XPath: Get parent node from child node What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing? How to use XPath preceding-sibling correctly Selenium and xPath - locating a link by containing text How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug? Concatenate multiple node values in xpath

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java

Examples related to webdriver

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? ImportError: No module named 'selenium' how to use List<WebElement> webdriver How to get attribute of element from Selenium? Selenium Finding elements by class name in python Open web in new tab Selenium + Python When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly How can I start InternetExplorerDriver using Selenium WebDriver