Right-click on an element using Selenium Python

There are certain situations where we need to perform a right-click action on a button or an element and choose from the dropdown options that appear. It may be necessary to perform similar actions while writing automated test scripts as well. In this post, we will discuss how to carry out a right-click action on an element using Selenium and Python. This will allow you to effectively simulate user actions and interactions during test automation.

We will use the ActionChains class in Selenium Python to right-click on the element. It provides a context_click() method, which helps perform right-click user action on an element.

Importing the ActionsChains class
from selenium.webdriver.common.action_chains import ActionChains
Using the context_click method on an element
action = ActionChains(driver)
action.context_click(element).perform()
Example

We will right-click on the highlighted element in the below image. This element is present on our playground website – https://testkru.com/Elements/Buttons

Right click on me button

We can locate the element with the id “rightClick” using the find_element() method in Selenium with Python.

element = driver.find_element(By.ID, 'rightClick')

Then, we will use the context_click() method to right click on the element.

Whole code

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

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options)
driver.get("https://testkru.com/Elements/Buttons")

element = driver.find_element(By.ID, 'rightClick')

action = ActionChains(driver)
action.context_click(element).perform() #right clicking on the element

Above code will right click on the element which is also indicated by the change in the button text.

right clicked on the button

This is it. We hope that you like the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Related Article
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *