How to perform right click using Selenium ChromeDriver?

…衆ロ難τιáo~ 提交于 2019-12-05 18:02:37

问题


I have been searching for this a lot, but could not find an answer for Python.

Is it possible to simulate right click, or open up the context menu via selenium/chromedriver?

I have seen options for Java, and some other languages, but never in Python. What would I have to do to simulate a right click on a link, or a picture?


回答1:


It's called context_click in selenium.webdriver.common.action_chains. Note that Selenium can't do anything about browser level context menu, so I assume your link will pop up HTML context menu.

from selenium import webdriver
from selenium.webdriver import ActionChains

driver = webdriver.Chrome()
actionChains = ActionChains(driver)

actionChains.context_click(your_link).perform()



回答2:


I encountered to the same issue where I had to right click and click on 'open link in new tab'. I searched for lot of answers on google but there was no specific solution i found for python. Earlier, i was doing using 'ActionChains' where right click menu is showing, but then that menu list can't be accessed in selenium as i found some threads saying this has OS level access.

action = ActionChains(driver) action.context_click().send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform()

Here, Keys.ARROW_DOWN is not working and opening the link in same tab, ideally it should open in new tab. So, there are two ways through which i done this:

  1. link = driver.find_elements_by_xpath("//a[contains(@href, 'https:...')]")

    link.send_keys(Keys.CONTROL + Keys.ENTER)

  2. Through javascript..

    driver.execute_script("window.open(arguments[0], '_blank');", link)

What i think you can't access the right click menu items in selenium as it is out of it's scope.




回答3:


You can perform context click using ActionChains, and use Arrows via send_keys to select an element from the context menu.

ActionChains(context.browser).move_to_element(element).context_click(element).perform()
ActionChains(context.browser).send_keys(Keys.ARROW_UP).perform()
ActionChains(context.browser).send_keys(Keys.ENTER).perform()


来源:https://stackoverflow.com/questions/20316864/how-to-perform-right-click-using-selenium-chromedriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!