Cam*_*Ice 10 python selenium webdriver selenium-chromedriver selenium-webdriver
我一直在寻找这个,但找不到Python的答案.
是否可以模拟右键单击,或通过selenium/chromedriver打开上下文菜单?
我见过Java和其他一些语言的选项,但从未在Python中看到过.如何模拟右键单击链接或图片,我需要做些什么?
Yi *_*eng 10
它context_click在selenium.webdriver.common.action_chains中调用.请注意,Selenium无法对浏览器级别的上下文菜单执行任何操作,因此我假设您的链接将弹出HTML上下文菜单.
from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome()
actionChains = ActionChains(driver)
actionChains.context_click(your_link).perform()
Run Code Online (Sandbox Code Playgroud)
要浏览上下文菜单,我们必须使用 pyautogui 和 selenium。使用pyautogui的原因是我们需要控制鼠标来控制上下文菜单上的选项。为了演示这一点,我将使用 python 代码在新选项卡中自动打开《复仇者联盟:终局之战》的 google 图像。
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import pyautogui
URL = 'https://www.google.com/'
PATH = r'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
action = ActionChains(driver)
driver.get(URL)
search = driver.find_element_by_name('q')
search.send_keys('Avengers Endgame')
search.send_keys(Keys.RETURN)
image_tab = driver.find_element_by_xpath('//a[text()="Images"]')
image_tab.click()
required_image = driver.find_element_by_xpath('//a[@class="wXeWr islib nfEiy mM5pbd"]')
action.context_click(required_image).perform()
pyautogui.moveTo(120, 130, duration=1)
pyautogui.leftClick()
time.sleep(1)
pyautogui.moveTo(300,40)
pyautogui.leftClick()
Run Code Online (Sandbox Code Playgroud)
现在在上面的代码中,直到 pyautogui.moveTo(120, 130,uration=1) 的部分是基于 selenium 的。您的答案从 pyautogui.moveTo(120, 130,uration=1) 开始,其作用只是将鼠标按钮移动到上下文菜单的新选项卡选项中打开的图像(请注意,屏幕坐标可能会根据您的情况而有所不同)屏幕尺寸)。下一行单击该选项(使用 action.click().perform() 将无法按预期工作)。
接下来的两行有助于在打开后导航到该选项卡。希望代码有帮助!