Select a drop-down menu option value with Selenium using Python

How to select a drop-down menu option value with Selenium using Python

We have a requirement to select an option from the drop-down menu, then we can use Selenium Webdriver. Here I am using Python language to choose the Option value from the Drop-Down menu. Here is the HTML page:

<select id="opt" class="opt">

    <option value="1" class="item">1</option>

    <option value="2" class="item">2</option>

    <option value="3" class="item">3</option>

    <option value="4" class="item">4</option>

    <option value="5" class="item">5</option>

    <option value="6" class="item">6</option>

    <option value="7" class="item">7</option>

    <option value="8" class="item">8</option>

    <option value="9" class="item">9</option>

    <option value="10" class="item">10</option>

</select>

So in this case we can select option value in 3 ways.

  • select_by_visible_text (Text) – We need to pass here visible text as a value that we want to select.

         Syntax−

         sel = Select (driver.find_element_by_id ("name"))

         sel.select_by_visible_text ('Visible Text')

  • select_by_value (Value) – We need to pass here text as a value that we want to select.

         Syntax−

         sel = Select (driver.find_element_by_id ("name"))

         sel.select_by_value ('Value')

  • select_by_index (Index) – We need to pass here the Index of text that we want to select.

         The index begins from zero.

         Syntax−

         sel = Select (driver.find_element_by_id ("name"))

         sel.select_by_index (1)

 

Here is the full example.

from selenium import webdriver

from selenium.webdriver.support.select import Select

import time

driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")

time.sleep(5)

driver.get("http://avitguru.com/") #give the url

# identify dropdown with Select ID

sel = Select(driver.find_element_by_xpath("//select[@id='opt']"))

# identify dropdown with Select Class

sel = Select(driver.find_element_by_class_name("opt"))

# identify dropdown with Select ID

sel = Select(driver.find_element_by_id("opt"))

#select by select_by_visible_text() method

sel.select_by_visible_text("1")

#select by select_by_index() method

sel.select_by_index(0)

#select by select_by_value() method

sel.select_by_index("1")

driver.close()

 

 

 

 

Akash Vishwakarma

Hi This is Akash Vishwakarma. I am working as software developer. I have knowledge in VBA, SQL Server, Python. I have developed this website from Django Framework.