Popular Searches
Popular Course Categories
Popular Courses

Dropdowns

HTML & Web Elements

<div class="selenium-notes">

<h1>Dropdowns in Selenium</h1>

<p>Dropdowns are one of the most commonly used web elements in web applications. They allow users to select one option from a predefined list of values or, in some cases, select multiple options. In Selenium WebDriver, dropdowns can be automated using different techniques depending on whether the dropdown is a standard HTML <code>&lt;select&gt;</code> element, a custom dropdown, a searchable dropdown, an autocomplete component, or a dynamically generated list.</p>

<p>These notes provide a detailed understanding of dropdown handling in Selenium WebDriver using Java, including locating dropdowns, selecting options, validating selections, handling dynamic dropdowns, custom dropdowns, multi-select dropdowns, searchable dropdowns, waits, JavaScript techniques, exceptions, Page Object Model, TestNG, reusable utilities, real-world scenarios, best practices, and interview questions.</p>

<p>For structured Selenium automation learning, you can explore the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a> and use the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a> option for course-related information.</p>

<hr>

<h2>1. What is a Dropdown?</h2>

<p>A dropdown is a user-interface component that displays a list of available options when the user interacts with it. Instead of displaying all options permanently, a dropdown saves screen space and allows the user to select a required value.</p>

<p>Examples of dropdowns include:</p>

<ul>

<li>Country selection</li>

<li>State selection</li>

<li>City selection</li>

<li>Gender selection</li>

<li>Category selection</li>

<li>Payment method selection</li>

<li>Language selection</li>

<li>Month and year selection</li>

<li>Product category selection</li>

<li>Account type selection</li>

</ul>

<h2>2. Dropdowns in Selenium Automation</h2>

<p>In Selenium automation, dropdown handling depends on the HTML implementation of the dropdown.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Dropdown Type</th><th>Common HTML Structure</th><th>Recommended Selenium Approach</th></tr>

<tr><td>Standard Dropdown</td><td><code>&lt;select&gt;</code></td><td><code>Select</code> class</td></tr>

<tr><td>Custom Dropdown</td><td><code>&lt;div&gt;</code>, <code>&lt;li&gt;</code>, buttons</td><td>Normal Selenium locators and clicks</td></tr>

<tr><td>Searchable Dropdown</td><td>Input + list</td><td>Send keys and select option</td></tr>

<tr><td>Autocomplete</td><td>Input + dynamic suggestions</td><td>Wait and select suggestion</td></tr>

<tr><td>Multi-Select</td><td><code>&lt;select multiple&gt;</code></td><td><code>Select</code> class</td></tr>

<tr><td>Dynamic Dropdown</td><td>Options generated dynamically</td><td>Explicit waits and dynamic locators</td></tr>

</table>

<hr>

<h2>3. Basic HTML Dropdown</h2>

<p>A standard HTML dropdown is generally created using the <code>&lt;select&gt;</code> element and multiple <code>&lt;option&gt;</code> elements.</p>

<pre><code>&lt;select id="country"&gt;

    &lt;option value="india"&gt;India&lt;/option&gt;

    &lt;option value="usa"&gt;United States&lt;/option&gt;

    &lt;option value="uk"&gt;United Kingdom&lt;/option&gt;

    &lt;option value="canada"&gt;Canada&lt;/option&gt;

&lt;/select&gt;</code></pre>

<p>Here, <code>&lt;select&gt;</code> represents the dropdown and each <code>&lt;option&gt;</code> represents an available value.</p>

<hr>

<h2>4. Understanding the Option Element</h2>

<p>Each dropdown option generally contains visible text and a value attribute.</p>

<pre><code>&lt;option value="india"&gt;India&lt;/option&gt;</code></pre>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Part</th><th>Meaning</th></tr>

<tr><td><code>option</code></td><td>Defines an item inside the dropdown</td></tr>

<tr><td><code>value="india"</code></td><td>Internal value of the option</td></tr>

<tr><td>India</td><td>Visible text displayed to the user</td></tr>

</table>

<hr>

<h2>5. Setting Up Selenium</h2>

<p>A basic Selenium Java project requires Selenium WebDriver and a browser driver or Selenium Manager-supported browser setup.</p>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class DropdownExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://example.com");

    }

}</code></pre>

<hr>

<h2>6. Locating a Dropdown Using ID</h2>

<p>If the dropdown has a unique <code>id</code>, the ID locator is usually a simple way to locate it.</p>

<pre><code>WebElement country = driver.findElement(By.id("country"));</code></pre>

<hr>

<h2>7. Locating a Dropdown Using Name</h2>

<p>The <code>name</code> attribute can also be used to locate a dropdown.</p>

<pre><code>WebElement country = driver.findElement(By.name("country"));</code></pre>

<hr>

<h2>8. Locating a Dropdown Using Class Name</h2>

<p>If a suitable unique class name exists, Selenium can locate the dropdown using <code>className()</code>.</p>

<pre><code>WebElement country = driver.findElement(By.className("country-select"));</code></pre>

<p>Avoid using class names that are generated dynamically or shared by many unrelated elements.</p>

<hr>

<h2>9. Locating a Dropdown Using Tag Name</h2>

<p>A standard dropdown uses the <code>select</code> HTML tag.</p>

<pre><code>WebElement dropdown = driver.findElement(By.tagName("select"));</code></pre>

<p>Tag name should normally be combined with another strategy when a page contains multiple dropdowns.</p>

<hr>

<h2>10. Locating a Dropdown Using CSS Selector</h2>

<p>CSS selectors provide flexible ways to locate dropdowns.</p>

<pre><code>WebElement dropdown = driver.findElement(By.cssSelector("#country"));</code></pre>

<p>Another example:</p>

<pre><code>WebElement dropdown = driver.findElement(By.cssSelector("select[name='country']"));</code></pre>

<hr>

<h2>11. CSS Selector Using Attribute</h2>

<pre><code>WebElement dropdown = driver.findElement(

    By.cssSelector("select[id='country']")

);</code></pre>

<hr>

<h2>12. CSS Selector Using Multiple Attributes</h2>

<pre><code>WebElement dropdown = driver.findElement(

    By.cssSelector("select[name='country'][id='country']")

);</code></pre>

<hr>

<h2>13. Locating Dropdown Using XPath</h2>

<p>XPath is commonly used when the dropdown does not have a simple unique ID or when a relationship with other elements is required.</p>

<pre><code>WebElement dropdown = driver.findElement(

    By.xpath("//select[@id='country']")

);</code></pre>

<hr>

<h2>14. XPath Using Name</h2>

<pre><code>WebElement dropdown = driver.findElement(

    By.xpath("//select[@name='country']")

);</code></pre>

<hr>

<h2>15. XPath Using Multiple Attributes</h2>

<pre><code>WebElement dropdown = driver.findElement(

    By.xpath("//select[@id='country' and @name='country']")

);</code></pre>

<hr>

<h2>16. XPath Using Parent and Child Relationship</h2>

<pre><code>WebElement dropdown = driver.findElement(

    By.xpath("//div[@class='country-container']//select")

);</code></pre>

<hr>

<h2>17. What is the Select Class?</h2>

<p>Selenium provides the <code>Select</code> class for handling standard HTML dropdowns created using the <code>&lt;select&gt;</code> element.</p>

<pre><code>import org.openqa.selenium.support.ui.Select;</code></pre>

<p>The basic syntax is:</p>

<pre><code>WebElement dropdown = driver.findElement(By.id("country"));

Select select = new Select(dropdown);</code></pre>

<hr>

<h2>18. selectByVisibleText()</h2>

<p>The <code>selectByVisibleText()</code> method selects an option according to the text visible to the user.</p>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

select.selectByVisibleText("India");</code></pre>

<p>This is useful when the displayed option text is stable and known.</p>

<hr>

<h2>19. selectByValue()</h2>

<p>The <code>selectByValue()</code> method selects an option using its HTML <code>value</code> attribute.</p>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

select.selectByValue("india");</code></pre>

<p>For this HTML:</p>

<pre><code>&lt;option value="india"&gt;India&lt;/option&gt;</code></pre>

<p>the Selenium statement is:</p>

<pre><code>select.selectByValue("india");</code></pre>

<hr>

<h2>20. selectByIndex()</h2>

<p>The <code>selectByIndex()</code> method selects an option using its numerical position.</p>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

select.selectByIndex(0);</code></pre>

<p>Indexes normally start from <code>0</code>.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Index</th><th>Option</th></tr>

<tr><td>0</td><td>India</td></tr>

<tr><td>1</td><td>United States</td></tr>

<tr><td>2</td><td>United Kingdom</td></tr>

</table>

<p>Index-based selection should be used carefully because adding or removing options can change the indexes.</p>

<hr>

<h2>21. Complete Select Example</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

 

public class DropdownTest {

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        Select country = new Select(

            driver.findElement(By.id("country"))

        );

 

        country.selectByVisibleText("India");

 

        driver.quit();

    }

}</code></pre>

<hr>

<h2>22. Get All Dropdown Options</h2>

<p>The <code>getOptions()</code> method returns all options present in a standard dropdown.</p>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

 

List&lt;WebElement&gt; options = select.getOptions();</code></pre>

<p>Import the List class:</p>

<pre><code>import java.util.List;</code></pre>

<hr>

<h2>23. Print All Dropdown Options</h2>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

 

List&lt;WebElement&gt; options = select.getOptions();

 

for (WebElement option : options) {

    System.out.println(option.getText());

}</code></pre>

<hr>

<h2>24. Count Dropdown Options</h2>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

 

List&lt;WebElement&gt; options = select.getOptions();

 

System.out.println("Total options: " + options.size());</code></pre>

<hr>

<h2>25. Get Selected Option</h2>

<p>The <code>getFirstSelectedOption()</code> method returns the currently selected option.</p>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

 

WebElement selected = select.getFirstSelectedOption();

 

System.out.println(selected.getText());</code></pre>

<hr>

<h2>26. Verify Selected Option</h2>

<pre><code>Select select = new Select(driver.findElement(By.id("country")));

 

select.selectByVisibleText("India");

 

String selectedText = select

    .getFirstSelectedOption()

    .getText();

 

if (selectedText.equals("India")) {

    System.out.println("Correct option selected");

}</code></pre>

<hr>

<h2>27. Check Whether Dropdown Supports Multiple Selection</h2>

<p>The <code>isMultiple()</code> method determines whether the dropdown allows multiple selections.</p>

<pre><code>Select select = new Select(driver.findElement(By.id("skills")));

 

if (select.isMultiple()) {

    System.out.println("Multiple selection supported");

} else {

    System.out.println("Single selection dropdown");

}</code></pre>

<hr>

<h2>28. Multi-Select Dropdown</h2>

<p>A multi-select dropdown may use the <code>multiple</code> attribute.</p>

<pre><code>&lt;select id="skills" multiple&gt;

    &lt;option value="java"&gt;Java&lt;/option&gt;

    &lt;option value="selenium"&gt;Selenium&lt;/option&gt;

    &lt;option value="sql"&gt;SQL&lt;/option&gt;

    &lt;option value="python"&gt;Python&lt;/option&gt;

&lt;/select&gt;</code></pre>

<hr>

<h2>29. Selecting Multiple Options</h2>

<pre><code>Select skills = new Select(

    driver.findElement(By.id("skills"))

);

 

skills.selectByVisibleText("Java");

skills.selectByVisibleText("Selenium");

skills.selectByVisibleText("SQL");</code></pre>

<hr>

<h2>30. Deselect All Options</h2>

<p>For a multi-select dropdown, <code>deselectAll()</code> removes all selected options.</p>

<pre><code>Select skills = new Select(

    driver.findElement(By.id("skills"))

);

 

skills.deselectAll();</code></pre>

<hr>

<h2>31. Deselect by Visible Text</h2>

<pre><code>skills.deselectByVisibleText("Java");</code></pre>

<hr>

<h2>32. Deselect by Value</h2>

<pre><code>skills.deselectByValue("java");</code></pre>

<hr>

<h2>33. Deselect by Index</h2>

<pre><code>skills.deselectByIndex(0);</code></pre>

<hr>

<h2>34. Get All Selected Options</h2>

<pre><code>List&lt;WebElement&gt; selectedOptions =

    skills.getAllSelectedOptions();

 

for (WebElement option : selectedOptions) {

    System.out.println(option.getText());

}</code></pre>

<hr>

<h2>35. Validate Number of Selected Options</h2>

<pre><code>List&lt;WebElement&gt; selectedOptions =

    skills.getAllSelectedOptions();

 

if (selectedOptions.size() == 3) {

    System.out.println("Three options are selected");

}</code></pre>

<hr>

<h2>36. Selecting an Option Dynamically</h2>

<p>Sometimes the option to be selected is stored in a variable.</p>

<pre><code>String countryName = "India";

 

Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText(countryName);</code></pre>

<p>This technique is useful for data-driven automation.</p>

<hr>

<h2>37. Selecting Based on User Test Data</h2>

<pre><code>String expectedCountry = "Canada";

 

Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText(expectedCountry);</code></pre>

<hr>

<h2>38. Selecting an Option Using a Loop</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

List&lt;WebElement&gt; options = country.getOptions();

 

for (WebElement option : options) {

 

    if (option.getText().equals("India")) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>39. Finding an Option Without Select Class</h2>

<p>For a standard dropdown, Selenium's <code>Select</code> class is preferred. However, an option can also be located directly.</p>

<pre><code>driver.findElement(

    By.xpath("//select[@id='country']//option[text()='India']")

).click();</code></pre>

<hr>

<h2>40. Custom Dropdown</h2>

<p>Not every dropdown uses the HTML <code>&lt;select&gt;</code> element. Modern applications frequently create custom dropdowns using <code>&lt;div&gt;</code>, <code>&lt;button&gt;</code>, <code>&lt;ul&gt;</code>, and <code>&lt;li&gt;</code>.</p>

<pre><code>&lt;div class="dropdown"&gt;

    &lt;button&gt;Select Country&lt;/button&gt;

    &lt;ul&gt;

        &lt;li&gt;India&lt;/li&gt;

        &lt;li&gt;Canada&lt;/li&gt;

        &lt;li&gt;Australia&lt;/li&gt;

    &lt;/ul&gt;

&lt;/div&gt;</code></pre>

<p>The Selenium <code>Select</code> class should not be used for this type of dropdown because it is not a real HTML <code>&lt;select&gt;</code> element.</p>

<hr>

<h2>41. Handling Custom Dropdown</h2>

<pre><code>driver.findElement(

    By.xpath("//button[text()='Select Country']")

).click();

 

driver.findElement(

    By.xpath("//li[text()='India']")

).click();</code></pre>

<hr>

<h2>42. Custom Dropdown Using CSS</h2>

<pre><code>driver.findElement(

    By.cssSelector(".country-dropdown")

).click();

 

driver.findElement(

    By.cssSelector(".country-option[data-value='india']")

).click();</code></pre>

<hr>

<h2>43. Searchable Dropdown</h2>

<p>A searchable dropdown contains an input field that allows users to type and filter options.</p>

<pre><code>&lt;input id="countrySearch" placeholder="Search country"&gt;</code></pre>

<p>Selenium can enter the required text and select the matching suggestion.</p>

<pre><code>WebElement search = driver.findElement(

    By.id("countrySearch")

);

 

search.sendKeys("India");</code></pre>

<hr>

<h2>44. Selecting Search Result</h2>

<pre><code>driver.findElement(

    By.xpath("//li[contains(text(),'India')]")

).click();</code></pre>

<hr>

<h2>45. Autocomplete Dropdown</h2>

<p>Autocomplete dropdowns dynamically display suggestions based on user input.</p>

<pre><code>driver.findElement(By.id("city"))

       .sendKeys("Mum");

 

driver.findElement(

    By.xpath("//li[contains(text(),'Mumbai')]")

).click();</code></pre>

<hr>

<h2>46. Dynamic Dropdown</h2>

<p>Dynamic dropdown options may appear after an API request or after another element is selected.</p>

<p>For example:</p>

<ol>

<li>Select Country.</li>

<li>Application loads states.</li>

<li>Select State.</li>

<li>Application loads cities.</li>

<li>Select City.</li>

</ol>

<hr>

<h2>47. Dependent Dropdown</h2>

<p>A dependent dropdown changes its options according to another dropdown.</p>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText("India");

 

Select state = new Select(

    driver.findElement(By.id("state"))

);

 

state.selectByVisibleText("Maharashtra");</code></pre>

<hr>

<h2>48. Handling Dynamic Options with Explicit Wait</h2>

<pre><code>WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement option = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//option[text()='Maharashtra']")

    )

);

 

option.click();</code></pre>

<hr>

<h2>49. Waiting for Custom Dropdown Option</h2>

<pre><code>WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

driver.findElement(By.id("country")).click();

 

WebElement option = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//li[text()='India']")

    )

);

 

option.click();</code></pre>

<hr>

<h2>50. Explicit Wait for Dropdown Visibility</h2>

<pre><code>WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement dropdown = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("country")

    )

);

 

dropdown.click();</code></pre>

<hr>

<h2>51. Explicit Wait for Clickability</h2>

<pre><code>WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement dropdown = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("country")

    )

);

 

dropdown.click();</code></pre>

<hr>

<h2>52. Implicit Wait</h2>

<p>An implicit wait tells Selenium to wait for a specified amount of time when locating elements.</p>

<pre><code>driver.manage().timeouts().implicitlyWait(

    Duration.ofSeconds(10)

);</code></pre>

<p>Implicit waits apply broadly to element searches, whereas explicit waits provide more targeted synchronization.</p>

<hr>

<h2>53. Explicit Wait vs Implicit Wait</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Implicit Wait</th><th>Explicit Wait</th></tr>

<tr><td>Scope</td><td>General element searches</td><td>Specific condition</td></tr>

<tr><td>Control</td><td>Lower</td><td>Higher</td></tr>

<tr><td>Dynamic dropdowns</td><td>Less precise</td><td>More suitable</td></tr>

<tr><td>Condition</td><td>Element presence</td><td>Visibility, clickability, presence, etc.</td></tr>

</table>

<hr>

<h2>54. JavaScript Click for Dropdown</h2>

<p>JavaScript can sometimes be used when a normal Selenium click is blocked by application-specific UI behavior.</p>

<pre><code>WebElement dropdown = driver.findElement(

    By.id("country")

);

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].click();",

    dropdown

);</code></pre>

<hr>

<h2>55. JavaScript for Selecting an Option</h2>

<p>JavaScript can directly manipulate a select element when necessary, although normal Selenium interaction should generally be preferred.</p>

<pre><code>JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].value='india';",

    dropdown

);</code></pre>

<p>After manipulating the DOM directly, the application may also require its associated change event to be triggered. Therefore, JavaScript should not be the default approach.</p>

<hr>

<h2>56. When Not to Use JavaScript</h2>

<ul>

<li>When normal Selenium click works correctly</li>

<li>When the application requires actual user-like interaction</li>

<li>When JavaScript bypasses important UI behavior</li>

<li>When direct DOM manipulation creates unreliable tests</li>

<li>When the application uses event handlers that are not triggered by the script</li>

</ul>

<hr>

<h2>57. Standard Dropdown vs Custom Dropdown</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Standard Dropdown</th><th>Custom Dropdown</th></tr>

<tr><td>Uses <code>&lt;select&gt;</code></td><td>Usually uses <code>&lt;div&gt;</code>, <code>&lt;button&gt;</code>, etc.</td></tr>

<tr><td>Uses Selenium <code>Select</code></td><td>Uses normal WebElement interactions</td></tr>

<tr><td>Supports selectByValue()</td><td>Does not support Select methods</td></tr>

<tr><td>Supports selectByIndex()</td><td>Requires custom locator</td></tr>

<tr><td>Easy to automate</td><td>May require waits and dynamic locators</td></tr>

</table>

<hr>

<h2>58. Registration Form Dropdown</h2>

<p>A registration form commonly contains dropdowns such as country, state, city, date of birth, education, and occupation.</p>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText("India");

 

Select state = new Select(

    driver.findElement(By.id("state"))

);

 

state.selectByVisibleText("Maharashtra");</code></pre>

<hr>

<h2>59. Gender Dropdown</h2>

<p>Some applications represent gender selection using a dropdown instead of radio buttons.</p>

<pre><code>Select gender = new Select(

    driver.findElement(By.id("gender"))

);

 

gender.selectByVisibleText("Male");</code></pre>

<hr>

<h2>60. Payment Method Dropdown</h2>

<pre><code>Select payment = new Select(

    driver.findElement(By.id("paymentMethod"))

);

 

payment.selectByVisibleText("Credit Card");</code></pre>

<hr>

<h2>61. Delivery Method Dropdown</h2>

<pre><code>Select delivery = new Select(

    driver.findElement(By.id("delivery"))

);

 

delivery.selectByVisibleText("Express Delivery");</code></pre>

<hr>

<h2>62. Product Category Dropdown</h2>

<pre><code>Select category = new Select(

    driver.findElement(By.id("category"))

);

 

category.selectByVisibleText("Electronics");</code></pre>

<hr>

<h2>63. Country-State-City Flow</h2>

<pre><code>Country

   |

   v

State

   |

   v

City

   |

   v

Submit</code></pre>

<p>This type of dependent dropdown flow is frequently automated in registration, address, shopping, and booking applications.</p>

<hr>

<h2>64. Verify Country Selection</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText("India");

 

String actual = country

    .getFirstSelectedOption()

    .getText();

 

if (actual.equals("India")) {

    System.out.println("Country verified");

}</code></pre>

<hr>

<h2>65. Verify Dropdown Contains an Option</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

boolean found = false;

 

for (WebElement option : country.getOptions()) {

    if (option.getText().equals("India")) {

        found = true;

        break;

    }

}

 

System.out.println("India available: " + found);</code></pre>

<hr>

<h2>66. Verify Number of Options</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

int count = country.getOptions().size();

 

System.out.println("Option count: " + count);</code></pre>

<hr>

<h2>67. Verify Default Option</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

String defaultValue = country

    .getFirstSelectedOption()

    .getText();

 

System.out.println("Default: " + defaultValue);</code></pre>

<hr>

<h2>68. Placeholder Option</h2>

<p>Many dropdowns contain a placeholder such as <code>Select Country</code>.</p>

<pre><code>&lt;option value=""&gt;Select Country&lt;/option&gt;

&lt;option value="india"&gt;India&lt;/option&gt;</code></pre>

<p>Automation should verify that the user selects a real option rather than leaving the placeholder selected.</p>

<hr>

<h2>69. Required Dropdown Validation</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

String selected = country

    .getFirstSelectedOption()

    .getAttribute("value");

 

if (selected == null || selected.isEmpty()) {

    System.out.println("Country is required");

}</code></pre>

<hr>

<h2>70. Dropdown Inside a Table</h2>

<p>Tables may contain dropdowns in individual rows.</p>

<pre><code>WebElement row = driver.findElement(

    By.xpath("//tr[td[text()='Product A']]")

);

 

Select status = new Select(

    row.findElement(By.tagName("select"))

);

 

status.selectByVisibleText("Approved");</code></pre>

<hr>

<h2>71. Selecting Dropdown in a Specific Table Row</h2>

<pre><code>WebElement row = driver.findElement(

    By.xpath("//tr[td[contains(text(),'Order 1001')]]")

);

 

WebElement dropdown = row.findElement(

    By.tagName("select")

);

 

Select orderStatus = new Select(dropdown);

 

orderStatus.selectByVisibleText("Shipped");</code></pre>

<hr>

<h2>72. Dropdown in Product Listing</h2>

<p>E-commerce applications may contain sorting and filtering dropdowns.</p>

<pre><code>Select sort = new Select(

    driver.findElement(By.id("sort"))

);

 

sort.selectByVisibleText("Price: Low to High");</code></pre>

<hr>

<h2>73. Dropdown in Modal</h2>

<p>When a dropdown is inside a modal, first ensure that the modal is visible.</p>

<pre><code>WebElement modal = driver.findElement(

    By.id("userModal")

);

 

WebElement dropdown = modal.findElement(

    By.id("country")

);

 

Select country = new Select(dropdown);

 

country.selectByVisibleText("India");</code></pre>

<hr>

<h2>74. Dropdown Inside an Iframe</h2>

<p>If the dropdown is inside an iframe, Selenium must switch to the iframe before locating the dropdown.</p>

<pre><code>driver.switchTo().frame("paymentFrame");

 

Select payment = new Select(

    driver.findElement(By.id("payment"))

);

 

payment.selectByVisibleText("Credit Card");

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>75. Nested Iframe Dropdown</h2>

<pre><code>driver.switchTo().frame("outerFrame");

driver.switchTo().frame("innerFrame");

 

Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText("India");

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>76. Dropdown in Shadow DOM</h2>

<p>Modern web applications may place dropdown elements inside Shadow DOM.</p>

<p>Selenium provides Shadow DOM support through the WebElement ShadowRoot API in supported versions.</p>

<pre><code>WebElement host = driver.findElement(

    By.cssSelector("custom-dropdown")

);

 

SearchContext shadowRoot = host.getShadowRoot();

 

WebElement dropdown = shadowRoot.findElement(

    By.cssSelector("select")

);</code></pre>

<hr>

<h2>77. Dynamic List Dropdown</h2>

<p>A custom dropdown may generate its options only after clicking the main element.</p>

<pre><code>driver.findElement(

    By.id("categoryDropdown")

).click();

 

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement option = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.xpath("//li[text()='Electronics']")

    )

);

 

option.click();</code></pre>

<hr>

<h2>78. Dynamic IDs in Dropdown</h2>

<p>Some applications generate dynamic IDs.</p>

<pre><code>WebElement dropdown = driver.findElement(

    By.xpath("//select[starts-with(@id,'country_')]")

);</code></pre>

<hr>

<h2>79. Dynamic Class Names</h2>

<p>When class names contain dynamic values, use stable attributes whenever possible.</p>

<pre><code>WebElement dropdown = driver.findElement(

    By.xpath("//select[contains(@class,'country')]")

);</code></pre>

<hr>

<h2>80. Dropdown Automation Flow</h2>

<pre><code>Open Application

       |

       v

Locate Dropdown

       |

       v

Identify Dropdown Type

       |

       +--------------------+

       |                    |

       v                    v

Standard Select        Custom Dropdown

       |                    |

       v                    v

Select Class           Click + Locate Option

       |                    |

       +---------+----------+

                 |

                 v

Verify Selection

                 |

                 v

Continue Test

                 |

                 v

Close Browser</code></pre>

<hr>

<h2>81. Common Dropdown Scenarios</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Scenario</th><th>Technique</th></tr>

<tr><td>Standard select</td><td><code>Select</code> class</td></tr>

<tr><td>Select by text</td><td><code>selectByVisibleText()</code></td></tr>

<tr><td>Select by value</td><td><code>selectByValue()</code></td></tr>

<tr><td>Select by position</td><td><code>selectByIndex()</code></td></tr>

<tr><td>Multiple selection</td><td><code>isMultiple()</code></td></tr>

<tr><td>Get all options</td><td><code>getOptions()</code></td></tr>

<tr><td>Get selected option</td><td><code>getFirstSelectedOption()</code></td></tr>

<tr><td>Custom dropdown</td><td>Click and locate option</td></tr>

<tr><td>Dynamic dropdown</td><td>Explicit wait</td></tr>

<tr><td>Searchable dropdown</td><td>Input + suggestion selection</td></tr>

</table>

<hr>

<h2>82. Dropdown Validation Checklist</h2>

<ul>

<li>Verify dropdown is displayed.</li>

<li>Verify dropdown is enabled.</li>

<li>Verify dropdown contains expected options.</li>

<li>Verify default option.</li>

<li>Select the required option.</li>

<li>Verify selected option.</li>

<li>Verify dependent dropdown behavior.</li>

<li>Verify invalid or empty selection.</li>

<li>Verify dynamic options.</li>

<li>Verify multi-select behavior when applicable.</li>

</ul>

<hr>

<h2>83. Common Mistakes</h2>

<ul>

<li>Using <code>Select</code> class for a custom dropdown</li>

<li>Using unstable dynamic locators</li>

<li>Using index when the order of options can change</li>

<li>Not waiting for dynamically loaded options</li>

<li>Ignoring iframe context</li>

<li>Ignoring Shadow DOM</li>

<li>Not validating the final selection</li>

<li>Using JavaScript unnecessarily</li>

<li>Using <code>Thread.sleep()</code> everywhere</li>

</ul>

<hr>

<h2>84. Bad Dropdown Locator</h2>

<pre><code>driver.findElement(

    By.xpath("//select[1]")

);</code></pre>

<p>This locator depends only on position and may become unreliable when the page structure changes.</p>

<hr>

<h2>85. Better Dropdown Locator</h2>

<pre><code>driver.findElement(

    By.id("country")

);</code></pre>

<p>A stable unique ID is generally easier to maintain.</p>

<hr>

<h2>86. Best Practices for Dropdown Automation</h2>

<ol>

<li>Identify the dropdown type before writing automation code.</li>

<li>Use the <code>Select</code> class only for real HTML <code>&lt;select&gt;</code> elements.</li>

<li>Prefer stable IDs and meaningful attributes.</li>

<li>Use visible text when business readability is important.</li>

<li>Use value when the value attribute is stable.</li>

<li>Avoid unnecessary index-based selection.</li>

<li>Use explicit waits for dynamic dropdowns.</li>

<li>Validate the selected option.</li>

<li>Use reusable dropdown utilities.</li>

<li>Avoid unnecessary JavaScript.</li>

</ol>

<hr>

<h2>87. Real-World Registration Scenario</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText("India");

 

Select state = new Select(

    driver.findElement(By.id("state"))

);

 

state.selectByVisibleText("Maharashtra");

 

Select city = new Select(

    driver.findElement(By.id("city"))

);

 

city.selectByVisibleText("Mumbai");</code></pre>

<hr>

<h2>88. Real-World E-Commerce Scenario</h2>

<pre><code>Select category = new Select(

    driver.findElement(By.id("category"))

);

 

category.selectByVisibleText("Electronics");

 

Select sort = new Select(

    driver.findElement(By.id("sort"))

);

 

sort.selectByVisibleText("Price: Low to High");</code></pre>

<hr>

<h2>89. Real-World Booking Scenario</h2>

<pre><code>Select passengers = new Select(

    driver.findElement(By.id("passengers"))

);

 

passengers.selectByVisibleText("2");</code></pre>

<hr>

<h2>90. Real-World Payment Scenario</h2>

<pre><code>Select payment = new Select(

    driver.findElement(By.id("paymentMethod"))

);

 

payment.selectByVisibleText("Credit Card");</code></pre>

<hr>

<h2>91. TestNG Dropdown Validation</h2>

<pre><code>import org.testng.Assert;

import org.testng.annotations.Test;

 

@Test

public void verifyCountry() {

 

    Select country = new Select(

        driver.findElement(By.id("country"))

    );

 

    country.selectByVisibleText("India");

 

    String actual =

        country.getFirstSelectedOption().getText();

 

    Assert.assertEquals(actual, "India");

}</code></pre>

<hr>

<h2>92. Complete TestNG Dropdown Test</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class DropdownTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.get("https://example.com");

    }

 

    @Test

    public void verifyCountryDropdown() {

 

        Select country = new Select(

            driver.findElement(By.id("country"))

        );

 

        country.selectByVisibleText("India");

 

        String selected =

            country.getFirstSelectedOption().getText();

 

        Assert.assertEquals(selected, "India");

    }

 

    @AfterMethod

    public void tearDown() {

        driver.quit();

    }

}</code></pre>

<hr>

<h2>93. Dropdown Using Page Object Model</h2>

<p>In Page Object Model, dropdown locators and interaction methods can be placed inside a page class.</p>

<pre><code>public class RegistrationPage {

 

    WebDriver driver;

 

    By country = By.id("country");

    By state = By.id("state");

 

    public RegistrationPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void selectCountry(String value) {

        Select select =

            new Select(driver.findElement(country));

 

        select.selectByVisibleText(value);

    }

 

    public void selectState(String value) {

        Select select =

            new Select(driver.findElement(state));

 

        select.selectByVisibleText(value);

    }

}</code></pre>

<hr>

<h2>94. Reusable Dropdown Utility</h2>

<pre><code>public class DropdownUtil {

 

    public static void selectByText(

            WebDriver driver,

            By locator,

            String text) {

 

        Select select =

            new Select(driver.findElement(locator));

 

        select.selectByVisibleText(text);

    }

}</code></pre>

<p>Usage:</p>

<pre><code>DropdownUtil.selectByText(

    driver,

    By.id("country"),

    "India"

);</code></pre>

<hr>

<h2>95. Reusable Select by Value Utility</h2>

<pre><code>public static void selectByValue(

        WebDriver driver,

        By locator,

        String value) {

 

    Select select =

        new Select(driver.findElement(locator));

 

    select.selectByValue(value);

}</code></pre>

<hr>

<h2>96. Dropdown Utility with Explicit Wait</h2>

<pre><code>public static void selectByText(

        WebDriver driver,

        By locator,

        String text) {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement element = wait.until(

        ExpectedConditions.visibilityOfElementLocated(locator)

    );

 

    Select select = new Select(element);

 

    select.selectByVisibleText(text);

}</code></pre>

<hr>

<h2>97. Selecting From Multiple Dropdowns</h2>

<pre><code>List&lt;WebElement&gt; dropdowns =

    driver.findElements(By.tagName("select"));

 

for (WebElement element : dropdowns) {

 

    Select select = new Select(element);

 

    System.out.println(

        select.getFirstSelectedOption().getText()

    );

}</code></pre>

<hr>

<h2>98. Finding Selected Option Using CSS</h2>

<p>For standard HTML dropdowns, the selected option may have the <code>selected</code> attribute.</p>

<pre><code>WebElement selected = driver.findElement(

    By.cssSelector("select#country option:checked")

);

 

System.out.println(selected.getText());</code></pre>

<hr>

<h2>99. CSS :checked Selector</h2>

<p>The <code>:checked</code> pseudo-class can be used for checked or selected form controls where supported by the browser and element type.</p>

<pre><code>WebElement selected = driver.findElement(

    By.cssSelector("#country option:checked")

);</code></pre>

<hr>

<h2>100. Verify Dropdown Has a Selection</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

WebElement selected =

    country.getFirstSelectedOption();

 

String text = selected.getText();

 

if (!text.equals("Select Country")) {

    System.out.println("Valid option selected");

}</code></pre>

<hr>

<h2>101. Count Selected Options</h2>

<pre><code>Select skills = new Select(

    driver.findElement(By.id("skills"))

);

 

int count =

    skills.getAllSelectedOptions().size();

 

System.out.println(

    "Selected options: " + count

);</code></pre>

<hr>

<h2>102. Verify Specific Value</h2>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

String value =

    country.getFirstSelectedOption()

           .getAttribute("value");

 

if (value.equals("india")) {

    System.out.println("India selected");

}</code></pre>

<hr>

<h2>103. Required Dropdown Group</h2>

<p>A required dropdown can be validated before submitting a form.</p>

<pre><code>Select country = new Select(

    driver.findElement(By.id("country"))

);

 

String value =

    country.getFirstSelectedOption()

           .getAttribute("value");

 

if (value == null || value.isEmpty()) {

    System.out.println(

        "Please select a country"

    );

}</code></pre>

<hr>

<h2>104. Dropdown Test Case Format</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Test Case</th><th>Expected Result</th></tr>

<tr><td>Verify dropdown displayed</td><td>Dropdown should be visible</td></tr>

<tr><td>Verify dropdown enabled</td><td>Dropdown should be enabled</td></tr>

<tr><td>Verify default option</td><td>Expected default should be selected</td></tr>

<tr><td>Select valid option</td><td>Option should be selected</td></tr>

<tr><td>Verify selection</td><td>Selected value should match expected value</td></tr>

<tr><td>Verify options</td><td>Expected options should be available</td></tr>

<tr><td>Verify dependent dropdown</td><td>Options should update correctly</td></tr>

<tr><td>Verify required validation</td><td>Validation should appear for empty selection</td></tr>

</table>

<hr>

<h2>105. Dropdown Test Data</h2>

<pre><code>Country     State          City

India       Maharashtra    Mumbai

India       Karnataka      Bengaluru

India       Delhi          New Delhi

Canada      Ontario        Toronto

USA         California     Los Angeles</code></pre>

<p>External test data can also be used with TestNG data providers, Excel, CSV, JSON, or other test-data sources.</p>

<hr>

<h2>106. Logging Dropdown Selection</h2>

<pre><code>String countryName = "India";

 

System.out.println(

    "Selecting country: " + countryName

);

 

Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText(countryName);

 

System.out.println(

    "Country selected successfully"

);</code></pre>

<hr>

<h2>107. Assertions for Dropdowns</h2>

<pre><code>String actual =

    country.getFirstSelectedOption().getText();

 

Assert.assertEquals(

    actual,

    "India",

    "Country selection is incorrect"

);</code></pre>

<hr>

<h2>108. Testing Dependent Dropdown Behavior</h2>

<ol>

<li>Select the parent dropdown.</li>

<li>Wait for child options to load.</li>

<li>Read available child options.</li>

<li>Verify the expected options.</li>

<li>Select the required child option.</li>

<li>Continue to the next dependent dropdown.</li>

</ol>

<hr>

<h2>109. Three-Option Dropdown</h2>

<pre><code>&lt;select id="plan"&gt;

    &lt;option value="basic"&gt;Basic&lt;/option&gt;

    &lt;option value="standard"&gt;Standard&lt;/option&gt;

    &lt;option value="premium"&gt;Premium&lt;/option&gt;

&lt;/select&gt;</code></pre>

<hr>

<h2>110. Select Premium Plan</h2>

<pre><code>Select plan = new Select(

    driver.findElement(By.id("plan"))

);

 

plan.selectByVisibleText("Premium");</code></pre>

<hr>

<h2>111. Verify Premium Plan</h2>

<pre><code>String selectedPlan =

    plan.getFirstSelectedOption().getText();

 

Assert.assertEquals(

    selectedPlan,

    "Premium"

);</code></pre>

<hr>

<h2>112. Verify Other Options</h2>

<pre><code>List&lt;WebElement&gt; options =

    plan.getOptions();

 

for (WebElement option : options) {

 

    if (!option.getText().equals("Premium")) {

        System.out.println(

            "Other option: " + option.getText()

        );

    }

}</code></pre>

<hr>

<h2>113. Interview Question: How Do You Handle Dropdowns in Selenium?</h2>

<p>For standard HTML dropdowns, Selenium provides the <code>Select</code> class. The dropdown WebElement is passed to the Select constructor, after which methods such as <code>selectByVisibleText()</code>, <code>selectByValue()</code>, and <code>selectByIndex()</code> can be used.</p>

<hr>

<h2>114. Interview Question: What is the Select Class?</h2>

<p>The <code>Select</code> class is a Selenium support class used to interact with HTML <code>&lt;select&gt;</code> elements.</p>

<hr>

<h2>115. Interview Question: How Do You Select by Visible Text?</h2>

<pre><code>Select select = new Select(

    driver.findElement(By.id("country"))

);

 

select.selectByVisibleText("India");</code></pre>

<hr>

<h2>116. Interview Question: How Do You Select by Value?</h2>

<pre><code>select.selectByValue("india");</code></pre>

<hr>

<h2>117. Interview Question: How Do You Select by Index?</h2>

<pre><code>select.selectByIndex(0);</code></pre>

<hr>

<h2>118. Interview Question: How Do You Get All Options?</h2>

<pre><code>List&lt;WebElement&gt; options =

    select.getOptions();</code></pre>

<hr>

<h2>119. Interview Question: How Do You Get the Selected Option?</h2>

<pre><code>WebElement selected =

    select.getFirstSelectedOption();</code></pre>

<hr>

<h2>120. Interview Question: How Do You Handle a Custom Dropdown?</h2>

<p>A custom dropdown does not use the standard HTML <code>&lt;select&gt;</code> element. Therefore, the Selenium <code>Select</code> class should not be used. Instead, locate and click the dropdown and then locate the desired option using appropriate XPath or CSS selectors.</p>

<hr>

<h2>121. Interview Question: What If a Dropdown Is Not Clickable?</h2>

<p>Possible causes include an overlay, animation, disabled element, incorrect locator, iframe, or synchronization issue. Use explicit waits, verify the element state, check the browser context, and inspect the page structure.</p>

<hr>

<h2>122. Interview Question: How Do You Handle a Hidden Dropdown?</h2>

<p>First determine how the application displays the dropdown. Some dropdowns become visible only after clicking a button. Use the actual user interaction to open the dropdown and then wait for the option to become visible or clickable.</p>

<hr>

<h2>123. Practical Project: Registration Form Automation</h2>

<p>Automate a registration page containing:</p>

<ul>

<li>Country dropdown</li>

<li>State dropdown</li>

<li>City dropdown</li>

<li>Education dropdown</li>

<li>Occupation dropdown</li>

</ul>

<p>Test flow:</p>

<ol>

<li>Open registration page.</li>

<li>Select country.</li>

<li>Wait for state options.</li>

<li>Select state.</li>

<li>Wait for city options.</li>

<li>Select city.</li>

<li>Select education.</li>

<li>Select occupation.</li>

<li>Validate every selected value.</li>

<li>Submit the form.</li>

<li>Verify successful registration.</li>

</ol>

<hr>

<h2>124. Advanced Project: E-Commerce Dropdown Automation</h2>

<p>Create an automation framework for an e-commerce website containing:</p>

<ul>

<li>Category dropdown</li>

<li>Brand filter</li>

<li>Price sorting dropdown</li>

<li>Availability filter</li>

<li>Product quantity dropdown</li>

<li>Country and delivery location dropdowns</li>

</ul>

<p>The framework should include:</p>

<ul>

<li>Page Object Model</li>

<li>Reusable dropdown utilities</li>

<li>Explicit waits</li>

<li>TestNG assertions</li>

<li>Data-driven testing</li>

<li>Logging</li>

<li>Screenshot capture</li>

<li>HTML reporting</li>

</ul>

<hr>

<h2>125. Best-Practice Summary</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Practice</th><th>Recommendation</th></tr>

<tr><td>Identify type</td><td>Determine whether it is standard or custom</td></tr>

<tr><td>Standard dropdown</td><td>Use Selenium <code>Select</code></td></tr>

<tr><td>Custom dropdown</td><td>Use normal WebElement interactions</td></tr>

<tr><td>Locator</td><td>Prefer stable attributes</td></tr>

<tr><td>Selection</td><td>Prefer visible text or stable value</td></tr>

<tr><td>Index</td><td>Use only when option order is stable</td></tr>

<tr><td>Dynamic options</td><td>Use explicit waits</td></tr>

<tr><td>Validation</td><td>Verify selected value</td></tr>

<tr><td>Framework</td><td>Use Page Object Model and reusable utilities</td></tr>

<tr><td>JavaScript</td><td>Use only when normal Selenium interaction is insufficient</td></tr>

</table>

<hr>

<h2>126. Conclusion</h2>

<p>Dropdown handling is an important Selenium WebDriver skill because dropdowns are widely used in registration forms, e-commerce applications, booking systems, payment pages, dashboards, and enterprise web applications. For standard HTML <code>&lt;select&gt;</code> elements, Selenium's <code>Select</code> class provides convenient methods such as <code>selectByVisibleText()</code>, <code>selectByValue()</code>, <code>selectByIndex()</code>, <code>getOptions()</code>, and <code>getFirstSelectedOption()</code>.</p>

<p>For custom, searchable, autocomplete, dependent, and dynamic dropdowns, testers must use appropriate locators, explicit waits, WebElement interactions, and application-specific strategies. Reliable dropdown automation should focus on stable locators, synchronization, validation, reusable utilities, and maintainable framework design.</p>

<p>For further Selenium automation learning, explore the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a>.</p>

<p>To register for a course demo, visit the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a> page.</p>

</div>

Previous Next
whatsapp