How to automate menu box/pop up of right click in Python Selenium?


We can automate right click action with Selenium webdriver in Python by using the ActionChains class. We have to create an object of the ActionChains class and then apply the relevant method on it.

In order to move the mouse to the element on which right click is to be performed, we shall use the move_to_element method and pass the element locator as a parameter.

Then apply context_click method to perform the right click. Finally, use the perform method to actually carry out these actions. Also, we have to add the statement from selenium.webdriver.common.action_chains import ActionChains in our code to work with ActionChains class.

Syntax

a = ActionChains(driver)
m= driver.find_element_by_id("hot-spot")
a.move_to_element(m)
a.context_click().perform

Example

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/context_menu")
#object of ActionChains
a = ActionChains(driver)
#identify element
m = driver.find_element_by_id("hot-spot")
#move mouse over element
a.move_to_element(m)
#perform right-click
a.context_click().perform()
#switch to alert
al = driver.switch_to.alert
#get alert text
s = al.text
print("Alert text: ")
print(s)
#accept alert
al.accept()
#close browser
driver.quit()

Output

Updated on: 06-Apr-2021

637 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements