How to Right Click in Selenium Python: Simple Guide
To right click in Selenium Python, use the
ActionChains class and its context_click() method on a web element. Then call perform() to execute the action.Syntax
The ActionChains class lets you perform complex mouse and keyboard actions. To right click, use context_click(element) where element is the target web element. Finish with perform() to run the action.
- ActionChains(driver): Creates an action chain for the browser.
- context_click(element): Prepares a right click on the element.
- perform(): Executes all actions queued in the chain.
python
from selenium.webdriver import ActionChains actions = ActionChains(driver) actions.context_click(element).perform()
Example
This example opens a webpage, finds an element by its CSS selector, and performs a right click on it. It demonstrates how to use ActionChains to trigger the context menu.
python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver import ActionChains import time # Setup WebDriver (Chrome in this example) driver = webdriver.Chrome() driver.get('https://swisnl.github.io/jQuery-contextMenu/demo.html') # Locate the button to right click button = driver.find_element(By.CSS_SELECTOR, 'span.context-menu-one.btn.btn-neutral') # Create ActionChains object actions = ActionChains(driver) # Perform right click on the button actions.context_click(button).perform() # Wait to see the context menu time.sleep(3) driver.quit()
Output
The browser opens the demo page, right clicks on the button, and the context menu appears for 3 seconds before closing.
Common Pitfalls
Common mistakes when right clicking in Selenium Python include:
- Not calling
perform()aftercontext_click(), so the action never runs. - Trying to right click on a
Noneelement because the locator failed. - Using deprecated or incorrect locators that do not find the element.
- Not waiting for the element to be visible or interactable before right clicking.
Always verify the element is found and visible before performing actions.
python
from selenium.webdriver.common.by import By from selenium.webdriver import ActionChains # Wrong: missing perform() actions = ActionChains(driver) actions.context_click(element) # This does nothing # Right: actions.context_click(element).perform()
Quick Reference
| Method | Description |
|---|---|
| ActionChains(driver) | Create an action chain object for the browser |
| context_click(element) | Prepare a right click on the specified element |
| perform() | Execute all actions queued in the chain |
Key Takeaways
Use ActionChains and context_click(element) to right click in Selenium Python.
Always call perform() to execute the right click action.
Ensure the target element is correctly located and visible before right clicking.
Common errors include missing perform() and invalid element locators.
Use explicit waits if the element may take time to appear before right clicking.