Get Selected Option Using Selenium WebDriver with Python



We can obtain the option selected in a dropdown with Selenium webdriver. The first_selected_option method fetches the option selected in the dropdown. Once the option is returned we need to apply a text method to get option text.

Let us consider the select dropdown Continents and fetch its selected item −

Example

from selenium import webdriver
from selenium.webdriver.support.select import Select
import time driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
# identify dropdown
s = Select(driver.find_element_by_xpath("//select[@name='continents']"))
#select by option index
s.select_by_index(4)
#get selected item with method first_selected_option
o= s.first_selected_option
#text method for selected option text
print("Selected option is: "+ o.text)
driver.close()

Output

Updated on: 2020-09-18T13:25:05+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements