Skip to content
CodeKruPro

Choose a dropdown option by visible text

Automation taskEasyAsked in: Accenture, Capgemini, Infosys, SaaS Labs, TCS, Wipro

One of the most asked tasks: "Select India from the country dropdown, then print the selected option." For a native <select> element, use Selenium's Select helper and choose by the text the user sees.

Select Dropdown Option by Visible Text

Select Dropdown by Visible Text

Selenium provides the Select class (from org.openqa.selenium.support.ui.Select) to interact with HTML <select> elements.

selectByVisibleText() selects an option based on what the user sees.

HTML Structure:

<select id="singleSelect">
  <option value="" disabled selected>Select Language</option>
  <option value="java">Java</option>
  <option value="python">Python</option>
  <option value="javascript">JavaScript</option>
  <option value="csharp">C#</option>
  <option value="ruby">Ruby</option>
</select>

Task:

  1. Navigate to https://testkru.com/Elements/Dropdowns
  2. Create a Select object for the dropdown with ID singleSelect
  3. Select "Java" by visible text
  4. Print the selected option's text

Expected output:

Selected: Java