如何使用 Python 在 Selenium 中执行元素右键点击?


我们可以借助 Action Chains 类在 Selenium 中执行元素右键点击操作。这些类通常用于自动化诸如上下文菜单点击、鼠标按钮操作、按键和鼠标移动等交互操作。

这些类型的操作主要在复杂场景中常见,例如拖放和将鼠标悬停在页面上的元素上。Action Chains 类的 方法由高级脚本使用。我们可以借助 Selenium 中的 Action Chains 来操作 DOM。

动作链对象以队列的形式实现 ActionChains,然后执行 perform() 方法。调用 perform() 方法后,动作链上的所有操作都将被执行。

创建 Action Chain 对象的方法如下所示:

  • 首先,我们需要导入 Action Chain 类,然后将驱动程序作为参数传递给它。

  • 现在,可以使用此对象执行所有动作链操作。

语法

创建 Action Chains 对象的语法:

from selenium import webdriver

# import Action chains
from selenium.webdriver import ActionChains
# create webdriver object
driver = webdriver.Firefox()
# create action chain object
action = ActionChains(driver)

创建 Action Chains 对象后,我们可以像一个排队的链一样,一个接一个地执行许多操作。

context_click() - 此方法对页面上的元素执行右键点击操作。

语法

context_click(args)

其中 args 是要右键点击的元素。如果省略,则执行当前鼠标位置的点击操作。

#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# right click operation
action.context_click(source)

示例

右键点击操作的代码实现。

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the source element
source= driver.find_element_by_xpath("//*[text()='Company']");
# action chain object creation
action = ActionChains(driver)
# right click operation and then perform
action.context_click(source).perform()
#to close the browser
driver.close()

更新于: 2020-07-29

5K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.