How To Handle Dropdowns In Selenium WebDriver Using Python?
In this tutorial, we will learn how to handle dropdowns in Selenium WebDriver using Python. We will explore different methods to select or deselect options from a dropdown and also discuss ways to handle multiple selections if allowed by the dropdown. Additionally, we will cover scenarios where an element is not interactable due to its invisibility or being obscured by another element. To get started with this tutorial, you should have basic knowledge of Python programming language and Selenium WebDriver. You can refer to our previous tutorials on Introduction to Selenium WebDriver and Installing Selenium WebDriver in Python for more information. Let's begin! ## Handling Dropdowns Using Select Class Selenium provides a built-in class named `Select` under the module `selenium.webdriver.support.ui`. This class is specifically designed to handle HTML SELECT tags, which are commonly used for creating dropdown menus in web applications. The `Select` class offers several methods that can be used to interact with a dropdown element: - `select_by_visible_text(value)` : Selects an option from the dropdown by its visible text. - `select_by_value(value)` : Selects an option from the dropdown by its value attribute. - `select_by_index(index)` : Selects an option from the dropdown by its index position. - `deselect_all()` : Deselects all selected options in a multi-select dropdown. - `deselect_by_visible_text(value)` : Deselects an option from the dropdown by its visible text. - `deselect_by_value(value)` : Deselects an option from the dropdown by its value attribute. - `deselect_by_index(index)` : Deselects an option from the dropdown by its index position. - `get_options()` : Returns a list of all options in the dropdown. - `get_all_selected_options()` : Returns a list of all currently selected options in the dropdown. Let's see how we can use these methods to interact with a dropdown element on a webpage. ### Example 1: Selecting an Option from Dropdown Consider the following HTML code snippet that contains a simple dropdown menu: ```html <select id="lang" name="lang"> <option value="java">Java</option> <option value="python">Python</option> <option value="csharp">C#</option> <option value="ruby">Ruby</option> <option value="javascript">JavaScript</option> </select> ``` We can use the `Select` class to interact with this dropdown as follows: ```python from selenium import webdriver from selenium.webdriver.support.ui import Select # initialize a new instance of Chrome browser and open the target url driver = webdriver.Chrome() # navigate to the URL containing the dropdown driver.get('https://pynishant.github.io/dropdown-selenium-python-select.html') # identify the select element with id="lang" using Selectors and select an option from it by its visible text dropdown = driver.find_element_by_id('lang') # creating a selenium Select webelement of html <select> tag selectElement = Select(driver.find_element_by_id('lang')) # using selenium webdriver's select class methods to find an option with visible text "Python" and selecting it selectElement.select_by_visible_text('Python') # print the selected value of dropdown print("Selected option from dropdown : "+selectElement.first_selected_option.get_attribute('innerText')) } ``` In this example, we first locate the `<select>` element using its ID attribute and then create a Selenium Select web element object for it. After that, we use the `select_by_visible_text()` method of the Select class to select an option from the dropdown by its visible text ("Python"). Finally, we print out the selected value of the dropdown using the `first_selected_option` property of the Select class. ### Example 2: Deselecting All Selected Options in a Multi-Select Dropdown Consider the following HTML code snippet that contains a multi-select dropdown menu: ```html <select id="lang2" name="lang2" multiple> <option value="java">Java</option> <option value="python">Python</option> <option value="csharp">C#</option> <option value="ruby">Ruby</option> <option value="javascript">JavaScript</option> </select> ``` We can use the `Select` class to interact with this multi-select dropdown as follows: ```python from selenium import webdriver from selenium.webdriver.support.ui import Select # initialize a new instance of Chrome browser and open the target url driver = webdriver.Chrome() # navigate to the URL containing the dropdown driver.get('https://pynishant.github.io/dropdown-selenium-python-select.html'); # identify the select element with id="lang2" using Selectors and check if attribute "multiple" is present in it. dropdown = driver.find_element_by_id('lang2') if dropdown.get_attribute("multiple"): # xpath selector to find the element with text "C#" and "PHP" respectively myOption = driver.find_element_by_xpath("//select[@multiple]/option[contains(text(), 'C#')]") myOption1 = driver.find_element_by_xpath("//select[@multiple]/option[contains(text(), 'PHP')]") # using actionchains to select multiple options ActionChains(driver).key_down(Keys.CONTROL).click(myOption).key_up(Keys.CONTROL).perform() # pausing program execution for few seconds time.sleep(2) ActionChains(driver).key_down(Keys.CONTROL).click(myOption1).key_up(Keys.CONTROL).perform() try: # creating a selenium Select webelement of html <select> tag dropdown = Select(driver.find_element_by_id('lang2')) # using selenium webdriver's select class methods to find all selected options and printing it's text. Ideally, here output should be "PHP, C#" print("All selected options using ActionChains : \n") for opt in dropdown.all_selected_options: print(opt.get_attribute('innerText')) # clearing the php selection we performed in last step dropdown.deselect_by_visible_text('PHP') # Again printing the active selections, this time output should be only c# print("Remaining selected options after deselecting PHP : \n") for opt in dropdown.all_selected_options: print(opt.get_attribute('innerText')) time.sleep(2) # Using selenium select class method to deselect all options dropdown.deselect_all() time.sleep(2) # Using different select class methods, to select multiple options # selecting by index, Java dropdown.select_by_index(3) time.sleep(2) # selecting by value - php dropdown.select_by_value('php') time.sleep(2) # selecting by text - python dropdown.select_by_visible_text('Python') # printing active selections - output should include all three php, python, java print("All selected options after selecting using different select class methods : \n") for opt in dropdown.all_selected_options: print(opt.get_attribute('innerText')) dropdown.deselect_all() # to select all possible options dropdown = Select(driver.find_element_by_id('lang2')) for opt in dropdown.options: dropdown.select_by_visible_text(opt.get_attribute("innerText")) # all four selected options should be output print("Selected option lists after selecting all of them : \n") for opt in dropdown.all_selected_options: print(opt.get_attribute('innerText')) driver.quit() except Exception as e: print(e) print("error") else: print("get_attribute didn't work!") ``` In this example, we first locate the `<select>` element using its ID attribute and then create a Selenium Select web element object for it. After that, we use the `key_down()`, `click()`, and `key_up()` methods of the ActionChains class to simulate pressing and releasing the CTRL key while clicking on multiple options in the dropdown. Then, we use different select class methods (`select_by_index()`, `select_by_value()`, and `select_by_visible_text()`) to select multiple options from the dropdown. Finally, we print out all currently selected options using the `all_selected_options` property of the Select class. ### Example 3: Handling Dropdowns with Invisible or Obscured Options Sometimes, you may encounter situations where an option in a dropdown is not visible or clickable due to some other element obscuring it. In such cases, you can use JavaScript executor feature of Selenium WebDriver to make the invisible/obscured option visible and clickable before interacting with it. Here's how you can do this: ```python from selenium import webdriver # initialize a new instance of Chrome browser and open the target url driver = webdriver.Chrome() # navigate to the URL containing the dropdown driver.get('https://pynishant.github.io/dropdown-visibility-demo.html') # identify the select element with id="lang1" using Selectors and try clicking invisible element langDropdown = driver.find_element_by_xpath('//select[@id="lang1"]') ActionChains(driver).click(langDropdown).perform() except Exception as e: print(e) pass # identify the select element with id="lang" using Selectors and try clicking visible element myOption = driver.find_element_by_xpath('//select[@id="lang"]/option[@value="python"]') ActionChains(driver).click(myOption).perform() # Get the selected value of element under target and element hovering target selectedOption = Select(driver.find_element_by_xpath('//select[@id="lang"]')) try: selected_option = selectedOption.first_selected_option.text except Exception as e: print(e) selected_option = "None" # Get the selected value of element under target and element hovering target selectedOption1 = driver.find_element_by_xpath('//select[@id="lang1"]/following-sibling::div[1]').text try: selected_option1 = selectedOption1.get_attribute("innerText") except Exception as e: print(e) selected_option1 = "None" # Print the selected values print("Selected option from dropdown : "+selected_option) print("Selected value of element under target and element hovering target : "+selected_option1) ``` In this example, we first locate the `<select>` element using its ID attribute and then create a Selenium Select web element object for it. After that, we try clicking on an invisible option in another dropdown menu (which is obscured by another element) using the ActionChains class. If this operation fails due to invisibilityerrorhandling dropdowns in your web application project tasks test automation cloud testing tools tools tools happy testing!!!?
Company
LambdaTest
Date published
March 8, 2021
Author(s)
Harshit Paul
Word count
3437
Hacker News points
None found.
Language
English