Hadj
Hadj

Reputation: 11

Right Click -Selenium - Python

I'm little bit struggling to find the correct way to perform a right click.

Here is a sample of my code:

click_Menu = driver.find_element_by_id("Menu")
print(click_Menu.text)
action.move_to_element(click_Menu)
action.context_click(on_element=click_Menu)
action.perform()

All the imports are there.And print(click_Menu.text) => returns "Menu", so the element has been found

Error :

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

I tried to add time.sleep() but the result is the same.

Any ideas please ?

Upvotes: 0

Views: 2254

Answers (3)

suba
suba

Reputation: 1440

This code will help you to solve the issue.

from selenium.webdriver import ActionChains

Identifying the source element

click_Menu= driver.find_element_by_xpath("your path")

or

click_Menu= driver.find_element_by_id("Menu")

Action chain object creation

action = ActionChains(driver)

Right-click operation and then perform

action.move_to_element(click_Menu).perform()
action.context_click(click_Menu).perform()

The easy way to overcome many of these types of errors is to just add some sort of delay:

import time
time.sleep(2) 

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193088

You simply need to pass only the element within context_click() as follows:

context_click(click_Menu)

Your effective line of code will be:

action.context_click(click_Menu)

Optimizing your code block:

click_Menu = driver.find_element(By.ID, "Menu")
ActionChains(driver).move_to_element(click_Menu).context_click(click_Menu).perform()

Upvotes: 0

Hadj
Hadj

Reputation: 11

Solution found.

I was using an old ActionChains object. So i reinstantiate it by creating a new one.

action1 = ActionChains(driver)

Upvotes: 0

Related Questions