Python+Selenium自動化 模擬鼠標操作
在webdriver中,鼠標的一些操作如:雙擊、右擊、懸停、拖動等都被封裝在ActionChains類中,我們只用在需要使用的時候,導入這個類就可以了。
0.ActionChains類提供的鼠標常用方法:
- perform():執行所有 ActionChains 中存儲的行為。
- context_click():右擊
- double_click():雙擊
- drag_and_drop():拖到
- move_to_element():鼠標懸停
注意:
- 使用之前需要引入 ActionChains 類。
from selenium.webdriver.common.action_chains import ActionChains
鼠標右擊實例
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains # 引入 ActionChains 類
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
# 定位到要右擊的元素
right_click = browser.find_element_by_link_text('新聞')
# 對定位到的元素執行鼠標右鍵操作
#ActionChains(driver):調用ActionChains()類,並將瀏覽器驅動browser作為參數傳入
#context_click(right_click):模擬鼠標雙擊,需要傳入指定元素定位作為參數
#perform():執行ActionChains()中儲存的所有操作,可以看做是執行之前一系列的操作
try:
ActionChains(browser).context_click(right_click).perform()
print('成功右擊')
except Exception as e:
print('fail')
#輸出內容:成功雙擊
注意:
- ActionChains(driver):調用ActionChains()類,並將瀏覽器驅動browser作為參數傳入
- context_click(right_click):模擬鼠標雙擊,需要傳入指定元素定位作為參數
- perform():執行ActionChains()中儲存的所有操作,可以看做是執行之前一系列的操作
1.鼠標右擊
- context_click():右擊
# 鼠標右擊
# 定位到要右擊的元素
right_click = browser.find_element_by_id("xx")
# 對定位到的元素執行右擊操作
ActionChains(browser).move_to_element(right_click ).perform()
2.鼠標雙擊
- double_click():雙擊
# 定位到要右擊的元素
double_click = browser.find_element_by_id('xx')
# 對定位到的元素執行鼠標右鍵操作
ActionChains(browser).context_click(double_click).perform()
3.鼠標拖動
- drag_and_drop(source,target):拖動
- source:開始位置;需要拖動的元素
- target:結束位置;拖到后需要放置的目的地元素
# 開始位置:定位到元素的原位置
source = driver.find_element_by_id("xx")
# 結束位置:定位到元素要移動到的目標位置
target = driver.find_element_by_id("xx")
# 執行元素的拖放操作
ActionChains(driver).drag_and_drop(source,target).perform()
4.鼠標懸停
- move_to_element():鼠標懸停
# 定位到要懸停的元素
move = driver.find_element_by_id("xx")
# 對定位到的元素執行懸停操作
ActionChains(driver).move_to_element(move).perform()