Selenium Get List of Elements

Profile picture for user arilio666

In Selenium, you can use the find_elements_by_* methods to locate multiple elements that match a given criterion. For example, to get a list of all elements with a particular class, you can use find_elements_by_class_name(class_name). 

To get a list of all elements with a specific tag name, you can use find_elements_by_tag_name(tag_name). And to get a list of all elements with a particular CSS selector, you can use find_elements_by_css_selector(css_selector).

Here is an example of using find_elements_by_class_name to get a list of all elements with the class "example":

        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://example.com");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        List<WebElement> elements = driver.findElementsByClassName("example");

This will return a list of WebElements you can then iterate over and interact with as needed.

Here are the equivalent examples in Java:

Texts are present for this autopract page with some items; we will use this as an example.


1.) Print the text of all elements:

        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://autopract.com/selenium/parents.html");
        driver.manage().window().maximize();
        List<WebElement> elements = driver.findElementsByXPath("//ul[@class='menu']");
        for (WebElement webElement : elements) {
            System.out.println(webElement.getText());
        }
  • We took the common element XPath of all the texts.
  • Then iterated over the advanced for loop and got the texts of all elements.

2.) Get tagname and attribute.

        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://autopract.com/selenium/parents.html");
        driver.manage().window().maximize();
        List<WebElement> elements = driver.findElementsByXPath("//ul[@class='menu']");
        for (WebElement webElement : elements) {
            System.out.println(webElement.getTagName());
            System.out.println(webElement.getAttribute("class"));
        }

  • Here we can see it fetched both tagname and attribute of the class.