How to Get Selected Text From Dropdown 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 all dropdown flex elements as Web elements using webdriver.findElements() function and css selector.
  4. Iterate over all these elements and get the data value of the one whose attribute aria-selected is true.

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

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

public class GetSelectedText {

    public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\SelectedText\\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://docs.google.com/forms/d/e/1FAIpQLSd3hbwlnuLuwVVnP3iEAjQwXQuZ7PuiTNMuuYe0TcHHYqZ6uQ/viewform";
        driver.get(siteLink);

        //set a value , first :
        driver.findElements(By.cssSelector("span.vRMGwf.oJeWuf")).get(0).click();
        driver.findElements(By.cssSelector("span.vRMGwf.oJeWuf")).get(9).click();

        //Get all dropdown elements
        List<WebElement> allElements = driver.findElements(By.cssSelector("div.MocG8c.HZ3kWc.mhLiyf.OIC90c.LMgvRb.KKjvXb"));
        //Get the Selected item
        for (WebElement e : allElements) {
            String selection = e.getAttribute("aria-selected");
            if (selection.equals("true")) {
                System.out.println("Dropdown Selected Text : " + e.getAttribute("data-value"));
                break;
            }

        }
    }
}

Output:

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

Comments