How to Handle Dropdowns in Python Selenium

When automating web applications, handling dropdown menus is a crucial task. Selenium WebDriver, a powerful tool for web automation, provides multiple ways to interact with dropdowns efficiently. In this guide, we will explore various methods to handle dropdowns in Python Selenium with practical examples.

What is a Dropdown in Selenium?

A dropdown menu is an HTML element that allows users to select an option from a list. These elements are commonly created using the <select> tag. Selenium provides the Select class to interact with such dropdown elements easily.

Importing Required Libraries

Before handling dropdowns, ensure you have Selenium installed in your Python environment.

Now, import the necessary modules:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select

Handling Dropdowns Using Selenium

1. Selecting an Option by Visible Text

This is the most common way to select an item from a dropdown. The select_by_visible_text() method is used to select an option based on its displayed text.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

# Initiate Webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)

# Launch dummy website
driver.get("https://automationbysqatools.blogspot.com/2021/05/dummy-website.html")

# Select dropdown one element
drop_down_element = driver.find_element(By.ID, "admorepass")
select_obj = Select(drop_down_element)

# Select dropdown option with select_by_visible_text
select_obj.select_by_visible_text("Add 1 more passenger (100%)")

# Select country dropdown element
country_dd = driver.find_element(By.ID, "billing_country")
select_obj2 = Select(country_dd)
select_obj2.select_by_visible_text("India")
time.sleep(5)

# Close the Browser
driver.close()

2. Selecting an Option by Index

If you know the position of the option, you can select it using select_by_index().

dropdown.select_by_index(2)  # Selects the third option (Index starts at 0)
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

# Initiate Webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)

# Launch dummy website
driver.get("https://automationbysqatools.blogspot.com/2021/05/dummy-website.html")

# Select add more passenger dropdown element
drop_down_element = driver.find_element(By.ID, "admorepass")
select_obj = Select(drop_down_element)

# Select value by select_by_index() method
select_obj.select_by_index(2)

# Select country dropdown element
country_dd = driver.find_element(By.ID, "billing_country")
select_obj2 = Select(country_dd)

# Select value by select_by_index() method
select_obj2.select_by_index(10)
time.sleep(5)

# Close the Browser
driver.close()

3. Selecting an Option by Value Attribute

Each dropdown option has a value attribute that can be used for selection.

dropdown.select_by_value("option2")  # Selects the option with value "option2"
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

# Initiate Webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)

# Launch dummy website
driver.get("https://automationbysqatools.blogspot.com/2021/05/dummy-website.html")

# Select add more passenger dropdown element
drop_down_element = driver.find_element(By.ID, "admorepass")
select_obj = Select(drop_down_element)

# Select dropdown option by value option
select_obj.select_by_value("3")

# Select country dropdown element
country_dd = driver.find_element(By.ID, "billing_country")
select_obj2 = Select(country_dd)
select_obj2.select_by_value("BE") # Belarus country
time.sleep(10)

# Close the Browser
driver.close()

4. Getting All Dropdown Options

Sometimes, you may need to extract all options from a dropdown.

options = dropdown.options
for option in options:
    print(option.text)  # Prints all available options

5. Deselecting Options (For Multi-Select Dropdowns)

If the dropdown allows multiple selections, you can deselect options using:

dropdown.deselect_by_index(1)
dropdown.deselect_by_value("option2")
dropdown.deselect_by_visible_text("Option 3")
dropdown.deselect_all()  # Clears all selections

Handling Non-Select Dropdowns

Some dropdowns are not built using the <select> tag. Instead, they rely on div, span, or ul/li elements. In such cases, JavaScript execution or direct element interaction is required.

1. Clicking to Reveal Options and Selecting One

dropdown_button = driver.find_element(By.XPATH, "//div[@class='dropdown']")
dropdown_button.click()

option_to_select = driver.find_element(By.XPATH, "//li[text()='Option 1']")
option_to_select.click()

2. Using JavaScript to Select an Option

For complex dropdowns, JavaScript can be used:

script = "document.querySelector('css-selector-for-dropdown').value='option_value'"
driver.execute_script(script)

Best Practices for Handling Dropdowns in Selenium

  • Use explicit waits to ensure the dropdown loads before interaction.
  • Handle stale element exceptions if dropdown updates dynamically.
  • Use appropriate selection methods based on the dropdown structure.
  • Validate selections by retrieving the selected option.

Handle Alerts in Python Selenium

Introduction to Handling Alerts in Python Selenium

Selenium is one of the most widely used frameworks for automating web browsers. It provides robust features to interact with web elements, navigate pages, and handle pop-ups efficiently. One of the critical aspects of web automation is handling alerts, which appear as pop-ups and require user interaction. In this comprehensive guide, we will explore the different types of alerts and how to handle them using Python Selenium.

Types of Alerts in Selenium

Alerts in Selenium can be broadly categorized into three types:

  1. Simple Alert – Displays a message with an OK button.
  2. Confirmation Alert – Displays a message with OK and Cancel buttons.
  3. Prompt Alert – Displays a message with an input field, allowing user input before clicking OK or Cancel.

Import Required Modules

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
import time

Handling Simple Alerts in Selenium

A simple alert consists of a message and an OK button. Selenium provides the switch_to.alert method to interact with alerts.

Example Code:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert

# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)

# Open a webpage with an alert
driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")

# Click button to launch alert
driver.find_element(By.ID, "btnShowMsg").click()
time.sleep(2)

# Create alert object
alert = Alert(driver)
print(alert.text)
time.sleep(2)

# Accept alert
alert.accept()

# Close browser
driver.quit()

Handling Confirmation Alerts in Selenium

A confirmation alert contains an OK and Cancel button, requiring user interaction.

Example Code:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert

# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)

# Open a webpage with an alert
driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")

confirm_btn = driver.find_element(By.ID, "button")
confirm_btn.click()
time.sleep(2)

# Create alert object
alert = Alert(driver)
print(alert.text)
time.sleep(2)

# Accept the alert
alert.accept()
UI_msg = driver.find_element(By.ID, "demo").text
print(UI_msg)
assert UI_msg == "You pressed OK!"

confirm_btn = driver.find_element(By.ID, "button")
confirm_btn.click()
# Dismiss the alert
alert.dismiss()

UI_msg_cancel = driver.find_element(By.ID, "demo").text
print(UI_msg_cancel)
assert UI_msg_cancel == "You pressed Cancel!"

# Close Browser
driver.quit()

Handling Prompt Alerts in Selenium

A prompt alert allows the user to enter input before dismissing the alert.

Example Code:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert

# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)

# Open a webpage with an alert
driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")

# Click button to launch prompt alert popup
prompt_box = driver.find_element(By.ID, "promptbtn")
prompt_box.click()
time.sleep(3)

# Create alert object
alert_prompt = Alert(driver)
new_value = "SQA"

# Send text to prompt box
alert_prompt.send_keys(new_value)
time.sleep(3)
# Accept the alert
alert_prompt.accept()

# Verify text on UI
ui_msg = driver.find_element(By.ID, "prompt")
expected_msg = f"Hello {new_value}! How are you today?"
assert ui_msg == expected_msg
time.sleep(5)


prompt_box = driver.find_element(By.ID, "promptbtn")
prompt_box.click()
time.sleep(3)

# Dismiss the prompt
alert_prompt.dismiss()
ui_msg = driver.find_element(By.ID, "prompt")
expected_msg = f"User cancelled the prompt."
assert ui_msg == expected_msg

# Close browser
driver.quit()

Best Practices for Handling Alerts in Selenium

  1. Use Explicit Waits: Instead of time.sleep(), use WebDriverWait to handle dynamic alerts.
  2. Validate Alert Text: Always verify the alert text before taking action.
  3. Handle NoAlertPresentException: Wrap alert handling in a try-except block to avoid exceptions if no alert appears.

Example Using WebDriverWait

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.alert import Alert

# Initialize WebDriver
driver = webdriver.Chrome()

driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")

try:
WebDriverWait(driver, 10).until(EC.alert_is_present())
driver.find_element(By.ID, "btnShowMsg").click()
time.sleep(2)
alert = Alert()
print("Alert found: ", alert.text)
alert.accept()
except:
print("No alert present")

# Close Browser
driver.quit()

Right Click in Python Selenium

Selenium provides the ability to automate right-click (context-click) operations using its ActionChains class. Right-clicking is essential for testing functionalities like context menus, custom event handlers, and hidden options in web applications. This article provides a comprehensive guide on how to perform right-click ( (context-click) operations in Selenium using Python.

Setting Up Selenium for Context-Click

To perform a context-click action, we need to:

  1. Identify the target element (the element where we want to perform a right-click).
  2. Use ActionChains to execute the context-click operation.

Importing Required Libraries

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import time

Locating Elements for Context-Click

To successfully perform a context-click operation, we must locate the element properly. The most common ways to locate elements in Selenium include:

  • By ID: driver.find_element(By.ID, “context-menu”)
  • By Class Name: driver.find_element(By.CLASS_NAME, “context-item”)
  • By XPath: driver.find_element(By.XPATH, “//*[@id=’context-menu’]”)

Performing Context-Click in Selenium using ActionChains

The ActionChains class provides the context_click() method, which allows us to automate right-click interactions in web applications.

import time
# install pyautogui library using below command
# pip install pyautogui
import pyautogui
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(15)

# Launch website on browserdriver.get("https://www.globalsqa.com/demo-site/draganddrop/")
about_element = driver.find_element(By.XPATH, "//div[@id='menu']//a[text()='About']")

action = ActionChains(driver)
# Perform context-click (right-click)
action.context_click(about_element).perform()

# Using pyautogui library to perform action context click
time.sleep(5)
pyautogui.press("up")
time.sleep(2)
pyautogui.press("enter")
time.sleep(5)

driver.quit()

Drag and Drop in Python Selenium

Selenium is a powerful tool for automating web browsers, and it supports drag-and-drop operations through its ActionChains class. Automating drag and drop is crucial for testing web applications that rely on interactive elements such as sortable lists, sliders, and draggable objects. This article will provide an in-depth guide on how to perform drag-and-drop operations in Selenium using Python

Setting Up Selenium for Drag and Drop

To perform a drag-and-drop action, we need to:

  1. Identify the source element (the element we want to drag).
  2. Identify the target element (the element where we want to drop the source element).
  3. Use ActionChains to execute the drag-and-drop operation.

Importing Required Libraries

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import time

Locating Elements for Drag and Drop

To successfully perform a drag-and-drop operation, we must locate the elements properly. The most common ways to locate elements in Selenium include:

  • By ID: driver.find_element(By.ID, “source-id”)
  • By Class Name: driver.find_element(By.CLASS_NAME, “source-class”)
  • By XPath: driver.find_element(By.XPATH, “//*[@id=’source’]”)

Performing Drag and Drop in Selenium using ActionChains

The ActionChains class provides the drag_and_drop() method, which allows us to automate drag-and-drop interactions in web applications.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(15)

driver.get("https://www.globalsqa.com/demo-site/draganddrop/")
# Switch to the iframe
iframe_element = driver.find_element(By.XPATH, "//iframe[@class='demo-frame lazyloaded']")
driver.switch_to.frame(iframe_element)

# Get source element
image_element = driver.find_element(By.XPATH, "//h5[text()='High Tatras']//parent::li")

# Get target element
trash_element = driver.find_element(By.ID, "trash")

# Create an ActionChains object
action = ActionChains(driver)

# Drag and drop image from one source to target element.
action.drag_and_drop(image_element, trash_element).perform()
time.sleep(5)

driver.quit()

Performing Drag and Drop Using Click and Hold Method

An alternative approach to executing drag and drop involves using click_and_hold(), move_to_element(), and release(). This method is useful when drag_and_drop() does not work due to JavaScript-based UI interactions.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(15)

# Launch a URL on browser
driver.get("https://www.globalsqa.com/demo-site/draganddrop/")

# Switch to the iframe
iframe_element = driver.find_element(By.XPATH, "//iframe[@class='demo-frame lazyloaded']")
driver.switch_to.frame(iframe_element)

# Get source element
image_element = driver.find_element(By.XPATH, "//h5[text()='High Tatras']//parent::li")

# Get target element
trash_element = driver.find_element(By.ID, "trash")

# Create an ActionChains object
action = ActionChains(driver)

# Perform drag and drop using an alternative method
action.click_and_hold(image_element).move_to_element(trash_element).release()
action.perform()
time.sleep(5)

driver.quit()

Mouse Hover Action In Selenium

Mastering Mouse Hover Action in Selenium with Python: A Comprehensive Guide

When delving into the realm of web automation, particularly with Selenium in Python, one often encounters scenarios where merely clicking elements is insufficient. There are instances where a more nuanced interaction—such as hovering over an element to trigger a dropdown or unveil hidden options—is indispensable. This is where Selenium’s ActionChains class becomes a pivotal asset.

Understanding the Significance of Mouse Hover Actions

Many modern web applications leverage hover effects to provide interactive user experiences. For instance, e-commerce websites frequently employ hover actions to reveal product details or additional purchase options. Automating such interactions necessitates simulating a user hovering their cursor over a designated web element, which can be effortlessly achieved using Selenium’s ActionChains.

Implementing Mouse Hover Using ActionChains

To execute a hover action, the ActionChains class provides the move_to_element() method, which simulates the cursor hovering over a specified element.

Step-by-Step Implementation

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import time

# Initialize WebDriver
driver = webdriver.Chrome()

# Open flipkart website
driver.get("https://www.flipkart.com/")  
driver.maximize_window()
driver.implicitly_wait(10)

# Locate the element to hover over
element_to_hover = driver.find_element(By.XPATH, "//div[@aria-label='Fashion']")

# Create an ActionChains object
actions = ActionChains(driver)

# Perform the hover action
actions.move_to_element(element_to_hover).perform()

# Pause to observe the effect
time.sleep(3)

# Closing the browser
driver.quit()

Exploring Advanced Hover Scenarios

  1. Hover and Click on a Revealed Element: In cases where an element becomes visible only after hovering, you can chain actions as follows:
    revealed_element = driver.find_element(By.XPATH, “//div[@aria-label=’Fashion’]”) actions.move_to_element(element_to_hover).click(revealed_element).perform()
  2. Hover Over Nested Elements: If you need to hover over multiple elements sequentially, chain multiple move_to_element() calls:
    submenu = driver.find_element(By.XPATH, “//div[@class=’submenu’]”) actions.move_to_element(element_to_hover).move_to_element(submenu).perform()
  3. Hover Using Offsets: Sometimes, elements may not have distinct locators, requiring precise control using coordinates:

 Python tuple program to join tuples if the initial elements of the sub-tuple are the same

This Python Tuple program will check the initial value of all sub-tuples, if the initial value of two sub-tuple are the same, then it will merge both the tuple.

Input:
[(3,6,7),(7,8,4),(7,3),(3,0,5)]

Output:
[(3,6,7,0,5),(7,8,4,3)]

				
					# take input list value that contains multiple tuples
l1 = [(3, 6, 7), (7, 8, 4), (7, 3), (3, 0, 5)]

# initiate  a variable to store the required output
output = []

# initiate a loop with range of length of list l1.
for i in range(len(l1)):
    # initiate nested loop
    for j in range(i+1, len(l1)):
        # check any two same tuple initial values are same
        if l1[i][0] == l1[j][0]:
            # if two tuple initial value are same, then combine both tuple.
            # and store in output list.
            output.append(tuple(list(l1[i]) + list(l1[j][1:])))
        else:
            continue

print(output)
				
			
Output:
				
					# Output:
[(3, 6, 7, 0, 5), (7, 8, 4, 3)]
				
			

Python tuple program to add row-wise elements in Tuple Matrix

This Python tuple program will add a tuple of values as row-wise elements in the tuple matrix.

Input:
A = [[(‘sqa’, 4)], [(‘tools’, 8)]]
B = (3,6)

Output:
[[(‘sqa’, 4,3)], [(‘tools’, 8,6)]]

				
					var_a = [[('sqa', 4)], [('tools', 8)]]
var_b = (3, 6)
print("Input A : ", var_a)
print("Input B : ", var_b)

output = []

# initiate a loop till length of var_a
for i in range(len(var_a)):
    # get tuple value with the help of indexing of var_a and connvert into list
    l1 = list(var_a[i][0])
    # check if value of i is less than length of var_b
    if i < len(var_b):
        # append new value to the list
        l1.append(var_b[i])
    # now convert list into tuple and append to output list
    output.append([tuple(l1)])

print(output)
				
			

Output:

				
					Input A :  [[('sqa', 4)], [('tools', 8)]]
Input B :  (3, 6)

Output : 
[[('sqa', 4, 3)], [('tools', 8, 6)]]
				
			

PyCharm Configuration for Windows OS

For installing PyCharm in your System go through the following steps:

  • Open a web browser (e.g., Google Chrome, Firefox, or Edge).1 2
  • Click on first link as shown in web browser ,go to the official JetBrains PyCharm website,or click Here .2 2
  • Visit the official PyCharm website at JETBRAINS and this web page will appear3 2
  • Once the page loads, you’ll see options for different editions of PyCharm.
    • Professional Edition: Paid version with advanced features.
    • Community Edition: Free version, ideal for Python programming.4 2
  • Click the Download button under the Community Edition section.5 2
  • You’ll be redirected to the download page.The website should automatically detect your operating system (Windows) and provide the correct installer.
    • If not, ensure Windows is selected in the operating system dropdown or button.
    • Click the Download button to start downloading the PyCharm Community Edition .exe installer.6 2
  • The installer file will begin downloading. Its name will look something like pycharm-community-<version>.exe.Wait for the download to finish. The file size is usually around 300–400 MB.
    • Locate the downloaded .exe file (usually in your Downloads folder).
    • Double-click the file to start the installation process.7 2
  • A setup wizard will appear. Follow these steps:
    • Welcome Screen: Click Next.
    • Choose Installation Path: Select or confirm the default location where PyCharm will be installed (e.g., C:\Program Files\JetBrains\PyCharm Community Edition). Then, click Next.8 2
  • Installation Options:
    • Check Create Desktop Shortcut (optional).
    • Check Update PATH variable (optional but recommended for easy access to PyCharm from the command line).
    • Check Add Open Folder as Project (optional).
    • Click Next.9 2
  • Choose Start Menu Folder: Leave the default or choose a custom folder for shortcuts. Click Install.
    • 10 2The installation will begin. This might take a few minutes.
    • 11 2
  • Once the installation is complete, check Run PyCharm Community Edition if you want to open it immediately.12 2
  • Open desktop and click on PyCharm Logo.13 2
  • This Dialogue Box will appear, when you click on desktop Shortcut .14 2
  • After PyCharm opens, create a new project:
    • Click New Project.
    • Choose a location and name for the project.15 1
  • If everything works as expected, your PyCharm setup is complete.16 1
  • Right Click on your project name and select new.17
  • In New select for New file Python file.18
  • Name your Python file , here “Trial”.19
  • Write a Trial program of printing a “Hello World” ,and to run that script right click on screen & select Run and Debug.22
  • This Will be the output of the “Trial”. # printing “Hello World “23

Python installation in Windows OS:

  • Open Google Chrome or any other web browser and search for Python. 1 1 e1737919354722
  • Visit the official Python website at python.org.2 1 e1737960267614
  • Navigate to the Downloads section and select the latest stable release for Windows.Choose the appropriate installer based on your system architecture:
  • For 64-bit systems: “Windows installer (64-bit)”
  • For 32-bit systems: “Windows installer (32-bit)”3 1 e1737960433455
  • Locate the downloaded installer file (e.g., python-3.x.x-amd64.exe) and double-click to run it.4 1
  • Check the box labeled “Add Python to PATH” to ensure you can run Python from the command line.Click on “Install Now” to proceed with the default installation.5 1
  • In the “Optional Features” section, you can select additional components like:
    • Documentation
    • pip (Python package installer)
    • tcl/tk and IDLE (Python’s Integrated Development and Learning Environment)
    • Python test suite
    • py launcher6 1
  • Click “Next” and in the “Advanced Options” section, you can:
    • Choose the installation location
    • Add Python to environment variables
    • Install for all users7 1
  • After selecting the desired options, click “Install” to begin the installation.8 19 1 e1737960510964
  • Verify the Installation:
    • Open the Command Prompt:
    • Press Win + R, type cmd, and press Enter.
  • pip --version run in command prompt and python --version.14 1 e1737961172208

Python Installation for MacOS:

  • Check System Requirements: Ensure your macOS version is 10.9 or later.
  • Go To google chrome and search python

seach on google

  • Visit Python’s Official Website: Open https://www.python.org and navigate to the “Downloads” section. The website will auto-detect the appropriate version for macOS.irst page for python
  • Wait until the installation take place & navigate in download bar. 4 e1737897166784
  • Open the .pkg file.5 e1737900198771
  • Click to continue.6 e1737900590266
  • Again click on continue.7 e1737900689287
  • Now click on Agree.8
  • Now complete the processing and click on Install Button.10 e1737901071202And move the python installer package to bin12 e1737902387634
  • Now close all the tabs and open IDLE python.11 e1737902149333
  • Open IDLE shell and try a hello world Program.14 e1737902564954
  • Simple “Hello World” program.16You can also check version in Terminal by giving the following command to check the version of python.
    python3 –versionScreenshot 2025 01 26 at 11.38.27 PM