在 WebDriver 中, 將這些關于鼠標操作的方法封裝在 ActionChains 類提供。
ActionChains 類提供了鼠標操作的常用方法:
perform(): 執行所有 ActionChains 中存儲的行為;
context_click(): 右擊;
double_click(): 雙擊;
drag_and_drop(): 拖動;
move_to_element(): 鼠標懸停。
鼠標懸停操作
from selenium import webdriver# 引入 ActionChains 類from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("https://www.baidu.cn")# 定位到要懸停的元素above = driver.find_element_by_link_text("設置")# 對定位到的元素執行鼠標懸停操作ActionChains(driver).move_to_element(above).perform()
……
from selenium.webdriver import ActionChains
導入提供鼠標操作的 ActionChains 類。
ActionChains(driver)
調用 ActionChains()類, 將瀏覽器驅動 driver 作為參數傳入。
move_to_element(above)
context_click()方法用于模擬鼠標右鍵操作, 在調用時需要指定元素定位。
perform()
執行所有 ActionChains 中存儲的行為, 可以理解成是對整個操作的提交動作。?
ActionChains方法列表
click(on_element=None) ——單擊鼠標左鍵
click_and_hold(on_element=None) ——點擊鼠標左鍵,不松開
context_click(on_element=None) ——點擊鼠標右鍵
double_click(on_element=None) ——雙擊鼠標左鍵
drag_and_drop(source, target) ——拖拽到某個元素然后松開
drag_and_drop_by_offset(source, xoffset, yoffset) ——拖拽到某個坐標然后松開
key_down(value, element=None) ——按下某個鍵盤上的鍵
key_up(value, element=None) ——松開某個鍵
move_by_offset(xoffset, yoffset) ——鼠標從當前位置移動到某個坐標
move_to_element(to_element) ——鼠標移動到某個元素
move_to_element_with_offset(to_element, xoffset, yoffset) ——移動到距某個元素(左上角坐標)多少距離的位置
perform() ——執行鏈中的所有動作
release(on_element=None) ——在某個元素位置松開鼠標左鍵
send_keys(*keys_to_send) ——發送某個鍵到當前焦點的元素
send_keys_to_element(element, *keys_to_send) ——發送某個鍵到指定元素