如何在使用 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 对象后,我们可以逐个执行众多操作,就像一个已排队的链条。
move_to_element() - 此方法执行将鼠标移动到页面上元素中央的操作。
语法
move_to_element(args)
其中,args 是要移动到的元素。
#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# move to element operation
action.move_to_element(source).click().perform()示例
移动到某个元素的代码实现。
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)
# move to the element and click then perform the operation
action.move_to_element(source).click().perform()
#to close the browser
driver.close()
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP