You need to introduce the ActionChains class before using it.
from selenium.webdriver.common.action_chains
import ActionChains Common mouse methods provided by ActionChains class:perform(): Perform all actions stored in ActionChains. context_click(): right-click
double_click(): double-click drag_and_drop(): drag to move_to_element(): mouse over
1. Right-click instance
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()中储存的所有操作,可以看做是执行之前一系列的操作
2. Right click with the mouse: context_click()
# 鼠标右击
# 定位到要右击的元素
right_click = browser.find_element_by_id("xx")
# 对定位到的元素执行右击操作
ActionChains(browser).move_to_element(right_click ).perform()
3. Double click the mouse: double_click()
#定位到要右击的元素
double_click = browser.find_element_by_id('xx')
# 对定位到的元素执行鼠标右键操作
ActionChains(browser).context_click(double_click).perform()
4. Mouse drag: 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()
5. Mouse over: move_to_element()
定位到要悬停的元素
move = driver.find_element_by_id("xx")
# 对定位到的元素执行悬停操作
ActionChains(driver).move_to_element(move).perform()