How to Select li Element in Selenium Java

Selenium is an open-source web-based automation tool that is implemented using a web driver. We will be using geckodriver because Selenium 3 enables geckodriver as the default WebDriver implementation for Firefox.

Pre-requisites:

  1. geckodriver.exe
  2. maven dependency selenium
 <dependency>
    <groupid>org.seleniumhq.selenium</groupid>
	<artifactid>selenium-java</artifactid>  
	<version>4.1.1</version> 
 </dependency>

Steps:

it's a 4 steps process:
  1. Set webdriver.gecko.driver and its' path as a system property.
  2. Set the firefox diver and browse to the website.
  3. Get list items as Web elements using webdriver.findElements() function and CSS selector.
  4. Iterate over all these elements to get text and HTML.

Let’s see all the above steps in the code. We will use Webelment.getAttribute(String name) function to get the data.

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

public class Selectli {

    public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\Select-li\\src\\main\\resources\\geckodriver.exe";

    public static void main(String[] args) {
        //set firefox webdriver
        System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH);
        WebDriver driver = new FirefoxDriver();

        //get the firefox browser & Browse the Website
        String siteLink = "https://en.wikipedia.org/wiki/List_of_presidents_of_Pakistan";
        driver.get(siteLink);

        //make li available
        driver.findElement(By.cssSelector("span.mw-collapsible-toggle.mw-collapsible-toggle-default.mw-collapsible-toggle-collapsed")).click();

        //Get the li content Div
        WebElement liElements = driver.findElement(By.cssSelector("div.sidebar-list-content.mw-collapsible-content"));

        //get all li items
        List<WebElement> ListItems = liElements.findElements(By.tagName("li"));

        //terate over each li to get text and innerHTML
        for (WebElement e : ListItems) {
            System.out.println("List Item Text : " + e.getText());
            System.out.println("List Item HTML : " + e.getAttribute("innerHTML") + "\n");
        }

    }
}

Output:

All resources used in this tutorial are attached:
  • source code
  • geckdriver.exe
Download

Comments