from selenium.webdriver import ActionChains
1、鼠標點擊
click:鼠標左擊
double_click:鼠標雙擊
context_click:鼠標右擊
btn = driver.find_element_by_id('su')
# 第一步:創建一個鼠標操作的對象
action = ActionChains(driver)
# 第二步:進行點擊動作(事實上不會進行操作,只是添加一個點擊的動作)
action.click(btn)
# 第三步:執行動作
action.perform()
2、鼠標移動
driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')
driver.implicitly_wait(5)
# 定位設置元素
set_ele = driver.find_element_by_xpath("//div[@id='u1']//a[text()='設置']")
# 第一步:創建一個鼠標操作的對象
action = ActionChains(driver)
# 第二步:進行移動
action.move_to_element(set_ele)
# 第三步:執行動作
action.perform()
# 三行代碼寫成一行:支持鏈式調用
ActionChains(driver).move_to_element(set_ele).perform()
# 等待高級設置可點擊
WebDriverWait(driver,5,0.2).until(
EC.element_to_be_clickable((By.XPATH,"//a[text()='高級搜索']"))
).click()
3、鼠標滑動
# 選擇拖動滑塊的節點
sli_ele = driver.find_element_by_id('tcaptcha_drag_thumb')
# ------------鼠標滑動操作------------
action = ActionChains(driver)
# 第一步:在滑塊處按住鼠標左鍵
action.click_and_hold(sli_ele)
# 第二步:相對鼠標當前位置進行移動
action.move_by_offset(100,0)
# 第三步:釋放鼠標
action.release()
# 執行動作
action.perform()
4、鼠標在一個元素上拖動到另一個元素
s = WebDriverWait(driver, 30, 0.5).until(
EC.visibility_of_element_located((By.ID, 'draggable'))
)
t = WebDriverWait(driver, 30, 0.5).until(
EC.visibility_of_element_located((By.ID, 'droppable'))
)
# ------------鼠標滑動操作------------
action = ActionChains(driver)
# 第一步:拖動元素
action.drag_and_drop(s, t)
# 執行動作
action.perform()
參考:https://www.cnblogs.com/erchun/p/12906324.html