In Webdriver, some of the mouse actions such as: Double-click, right-click, hover, drag and so on are encapsulated in the Actionchains class, we only use when necessary to use, import this class can be.
The 0.ActionChains class provides a common method of mouse:
- Perform (): Performs the behavior stored in all actionchains.
- Context_click (): Right-click
- Double_click (): Double-click
- Drag_and_drop (): Drag to
- Move_to_element (): Mouse hover
Attention:
- The Actionchains class needs to be introduced before use.
from selenium.webdriver.common.action_chains import ActionChains
Mouse Right-click instance
from selenium import webdriverfrom 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‘)#输出内容:成功双击
Attention:
- Actionchains (Driver): Call the Actionchains () class and pass the browser driver browser as a parameter
- Context_click (Right_click): Analog mouse Double-click, need to pass in the specified element positioning as a parameter
- Perform (): performs all the operations stored in Actionchains () as a series of operations prior to execution
1. Right-click
- Context_click (): Right-click
# 鼠标右击# 定位到要右击的元素right_click = browser.find_element_by_id("xx")# 对定位到的元素执行右击操作ActionChains(browser).move_to_element(right_click ).perform()
2. Double-click the mouse
- Double_click (): Double-click
# 定位到要右击的元素double_click = browser.find_element_by_id(‘xx‘)# 对定位到的元素执行鼠标右键操作ActionChains(browser).context_click(double_click).perform()
3. Drag the mouse
- Drag_and_drop (source,target): Drag
- Source: The starting position, the element that needs to be dragged
- Target: End position, drag to the destination element to be placed after
# 开始位置:定位到元素的原位置source = driver.find_element_by_id("xx")# 结束位置:定位到元素要移动到的目标位置target = driver.find_element_by_id("xx")# 执行元素的拖放操作ActionChains(driver).drag_and_drop(source,target).perform()
4. Mouse hover
- Move_to_element (): Mouse hover
# 定位到要悬停的元素move = driver.find_element_by_id("xx")# 对定位到的元素执行悬停操作ActionChains(driver).move_to_element(move).perform()
Python+selenium Automation Article--Analog mouse operation