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.
- Selenium Features
- Selenium Installation
- Selenium Locators
- XPath Fundamentals
- CSS Selectors Methods
- Different Browsers Execution
- find_element & find_elements
- Check Enabled Status
- Check Displayed Status
- Check Selected Status
- Selenium Waits
- Send_keys Method
- Click Method
- Get Text
- Get Attribute Value
- Get Current URL
- Forward, Back, Refresh
- Take Screenshot
- Handle Browser Tabs
- Handle iframe
- Mouse Hover
- Context-Click
- Drag & Drop
- Handle Alerts
- Handle Dropdown
- Execute Javascript
- Scroll To element
- Headless Mode Execution
- Chrome Options
- Keyboard Action
Setting Up Selenium for Context-Click
To perform a context-click action, we need to:
- Identify the target element (the element where we want to perform a right-click).
- 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)
driver.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()