selenium鼠標操作篇:鼠標懸停和偏移、拖動、長按


一、鼠標懸停
ActionChains對象調用move_to_element(元素),然后執行perform()
示例:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common import action_chains

driver = webdriver.Firefox()
# 打開百度首頁
driver.get("https://www.baidu.com")
# 定位首頁的設置按鈕
ele_setting = driver.find_element(By.XPATH, "//span[@id='s-usersetting-top']")
# 實例化ActionChains對象,並傳入driver
action = action_chains.ActionChains(driver)
# 將鼠標懸停在設置按鈕處
action.move_to_element(ele_setting).perform()

示例的最終效果為,鼠標停留在按鈕元素處

 

二、鼠標偏移
ActionChains對象調用move_to_element_off_offset(元素未知,x,y),然后執行perform()
示例:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common import action_chains

driver = webdriver.Firefox()
# 打開百度首頁
driver.get("https://www.baidu.com")
# 定位首頁的設置按鈕
ele_setting = driver.find_element(By.XPATH, "//span[@id='s-usersetting-top']")
ele_login = driver.find_element(By.XPATH, "//a[@class='s-top-login-btn c-btn c-btn-primary c-btn-mini lb']")
s_location = ele_setting.location
l_location = ele_login.location
# 實例化ActionChains對象,並傳入driver
action = action_chains.ActionChains(driver)
# 將鼠標懸停在設置按鈕處
action.move_to_element_with_offset(ele_setting,
                                   s_location["x"]-l_location["x"],
                                   s_location["y"]-l_location["y"]).perform()

 

三、鼠標長按
鼠標長按:ActionChains對象調用click_and_hold()方法,然后調用perform()執行。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common import action_chains

driver = webdriver.Firefox()
# 打開百度首頁
driver.get("https://www.baidu.com")
# 定位首頁的設置按鈕
ele_setting = driver.find_element(By.XPATH, "//span[@id='s-usersetting-top']")
# 實例化ActionChains對象,並傳入driver
action = action_chains.ActionChains(driver)
# 鼠標長按設置按鈕
action.click_and_hold(ele_setting)

 

四、鼠標拖動
拖動:
1,drag_and_drop(soure=起始元素, target=結束元素)
2,drag_and_drop_by_offset(soure=起始元素,xoffset,yoffset),其中xoffset是水平便宜了,yoffset是垂直偏移量。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM