selenium - webdriver actionchains 鼠标事件(右击、双击、悬停、拖动)
webdriver中,将鼠标的操作封装在ActionChains类中,常用方法如下:
- 右击:context_click()
- 双击:double_click()
- 悬停:move_to_element()
- 拖动:drag_and_drop()
- 执行:perform() 执行所有ActionChains 中存储的行为,可理解为对整个操作的提交动作
ps:对元素的click()方法,可模拟鼠标左键单击事件
1. 鼠标右击
模拟鼠标右键点击百度首页的新闻按钮
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # 导入鼠标操作的ActionChains类 import time driver = webdriver.Chrome() driver.get('http://www.baidu.com') right_click_element = driver.find_element_by_name('tj_trnews') ActionChains(driver).context_click(right_click_element).perform() # 将driver和需右击的元素传入,并提交动作 time.sleep(2) driver.close()
右击效果如下:
2. 鼠标双击
找到元素并双击
double_click_element = driver.find_element_by_name('tj_trnews') ActionChains(driver).double_click(double_click_element).perform() # 鼠标双击
3. 鼠标悬停
above = driver.find_element_by_link_text('更多产品') ActionChains(driver).move_to_element(above).perform()
悬停效果如下:
4. 鼠标拖放
source = driver.find_element_by_link_text('新闻') target = driver.find_element_by_xpath('//*[@id="form"]/span[1]/span') ActionChains(driver).drag_and_drop(source, target).perform() #将source元素拖动到target元素位置