Last modified: Dec 02, 2023 By Alexander Williams
Python Selenium: Right Click and Select Option - Examples
Example 1: Right Click and Select Option Using Action Chains
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to a webpage with a context menu
driver.get('https://example.com/context-menu')
# Find the element to right-click
target_element = driver.find_element_by_id('target-element')
# Use Action Chains to right-click and select an option
actions = ActionChains(driver)
actions.context_click(target_element).perform()
# Locate the context menu option and click it
context_menu_option = driver.find_element_by_id('context-menu-option')
context_menu_option.click()
# Close the browser
driver.quit()
Output:
# Right clicks on the target element and selects the context menu option
Example 2: Right Click and Select Option Using JavaScript Executor
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to a webpage with a context menu
driver.get('https://example.com/context-menu')
# Find the element to right-click
target_element = driver.find_element_by_id('target-element')
# Use JavaScript Executor to trigger a right-click event
driver.execute_script("arguments[0].dispatchEvent(new Event('contextmenu'));", target_element)
# Locate the context menu option and click it
context_menu_option = driver.find_element_by_id('context-menu-option')
context_menu_option.click()
# Close the browser
driver.quit()
Output:
# Right clicks on the target element and selects the context menu option using JavaScript
Example 3: Handle Right-Click with Context Menu Interaction
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
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to a webpage with a context menu
driver.get('https://example.com/context-menu')
# Find the element to right-click
target_element = driver.find_element_by_id('target-element')
# Use Action Chains to right-click and select an option
actions = ActionChains(driver)
actions.context_click(target_element).perform()
# Explicitly wait for the context menu to appear
context_menu_option_locator = (By.ID, 'context-menu-option')
context_menu_option = WebDriverWait(driver, 10).until(EC.presence_of_element_located(context_menu_option_locator))
# Click the context menu option
context_menu_option.click()
# Close the browser
driver.quit()
Output:
# Right clicks on the target element, waits for the context menu, and selects the option