This post was most recently updated on July 29th, 2024
Sometimes we need to select a value from drop down in selenium. This drop down list can be of country, state, city etc..
In selenium using python, we can select values from drop-down using following sample code snippet:
from selenium import webdriver.
from selenium.webdriver.support.ui import Select.
driver = webdriver.Chrome(‘D:\\chromedriver.exe’)
driver.get(‘url’)
select = Select(driver.find_element_by_id(‘Country’))
# select by visible text
select.select_by_visible_text(‘India’)
# select by value
select.select_by_value(’11’)
Decoding code
1. from selenium import webdriver: This line states that, from selenium module/library webdriver will be imported. Selenium library contains all the classes and implementations for webdriver.
2. from selenium.webdriver.support.ui import Select: This line states that, from selenium module/library Select will be imported.
3. driver = webdriver.Chrome(‘D:\\chromedriver.exe’): In this line of code, instance of Chrome Webdriver is created. Path for chrome driver executable file is mentioned inside the paranthesis
4. driver.get(‘url’): This is used to navigate to the specific url, which user wants to navigate.
5. select = Select(driver.find_element_by_id(‘Country’)): In this line of code, we find country using ‘id’.
6. select.select_by_visible_text(‘India’): In this line of code, we are selecting country: India by using ‘visible text’
7. select.select_by_value(’11’): In this line of code, we are selecting value by using ’11’