如何在 Python Selenium 中自动执行右键单击菜单框/弹出窗口?
seleniumautomation testingtesting tools
我们可以使用 Python 中的 Selenium webdriver 的 ActionChains 类自动执行右键单击操作。我们需要创建一个 ActionChains 类的对象,然后在其上应用相关方法。
为了将鼠标移动到要执行右键单击的元素上,我们需要使用 move_to_element 方法并将元素定位器作为参数传递。
然后应用 context_click 方法执行右键单击。最后,使用 perform 方法实际执行这些操作。此外,我们还必须在代码中添加 from selenium.webdriver.common.action_chains import ActionChains 语句,以便使用 ActionChains 类。
语法
a = ActionChains(driver)
m= driver.find_element_by_id("hot-spot")
a.move_to_element(m)
a.context_click().perform
示例
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
#设置 chromodriver.exe 路径
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#启动 URL
driver.get("https://the-internet.herokuapp.com/context_menu")
#ActionChains 对象
a = ActionChains(driver)
#识别元素
m = driver.find_element_by_id("hot-spot")
#将鼠标移到元素上
a.move_to_element(m)
#执行右键单击
a.context_click().perform()
#切换到警报
al = driver.switch_to.alert
#获取警报文本
s = al.text
print("警报文本: ")
print(s)
#接受警报
al.accept()
#关闭浏览器
driver.quit()
输出


