[selenium] Select option from dropdown box

There are two ways to do this, first find the xpath of the element of the option then issue a click method, but this method will not work on some website which monitors mouse hover event and enable the element if the mouse is hovered over the drop down box.

Another sure way of selecting the desired option from the drop down box is to use the selenium.webdriver.support.ui.Select, then select either by value or text depends on the available element in the web application.

This example uses this link: https://the-internet.herokuapp.com/dropdown

First find out the xpath of the drop down box element.

Right click and select copy > Xpath to get the xpath of this dropdox box element. If xpath does not work (very unlikely) try using css_selector.

The create a select object like this:

options = Select(driver.find_element_by_xpath('//*[@id="dropdown"]'))

from the dropdown box option element there are two options which have values 1 and 2.

Use the newly created Select object to select the value of the desired option.

Here is the example gif on how it works.

This is a demonstration on how to work with dropdown box during script execution.

Below is the code:

from webdriver_manager.firefox import GeckoDriverManager
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from time import sleep

url = "https://the-internet.herokuapp.com/dropdown"
driver = webdriver.Firefox(
    executable_path=GeckoDriverManager().install()
)
# The sleep function is to get a more stablized result by purposefully wait for 5 seconds.
driver.get(url)
sleep(5)
options = Select(driver.find_element_by_xpath('//*[@id="dropdown"]'))
# Selection option 2 from dropdown box.
options.select_by_value("2")
sleep(5)
options.select_by_value("1")
sleep(5)
driver.close()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s