Python Selenium鼠标键盘事件

在实际的web产品测试中,对于鼠标的操作,不单单只有click(),有时候
还要用到右击、双击、拖动等操作,这些操作包含在ActionChains类中。(所以先导入类)
from selenium.webdriver.common.action_chains import ActionChains

ActionChains类中鼠标操作常用方法:

⚫ context_click() :右击

⚫ double_click() :双击

⚫ drag_and_drop() :拖动

⚫ move_to_element() :鼠标移动到一个元素上

⚫ click_and_hold() :按下鼠标左键在一个元素上

1、context_click():右击
#mouse = ActionChains(driver)
#mouse.context_click().perform()
mouse是类的对象
perform是执行的意思
或者直接写成:
ActionChains(driver).context_click().perform()       

2、double_click():双击
ActionChains(driver).double_click().perform()  

3、drag_and_drop():拖动
ActionChains(driver).drag_and_drop().perform()

4、move_to_element():鼠标移动到一个元素上
ActionChains(driver).move_to_element(element).perform()

element = driver.find_element(By.XPATH,'//a[@name="tj_briicon"]')
ActionChains(driver).move_to_element(element).perform()
time.sleep(1)
driver.find_element(By.XPATH,'//div[@class="s-top-more-title c-font-normal c-color-t"]').click()

5、click_and_hold() :按下鼠标左键在一个元素上
 ActionChains(driver).click_and_hold(element).pause(10).release(element).perform()   

链条命令,可以写很长
Pause 按住10s
Release 释放、放开
Perform 执行

 1 import time
 2 
 3 from selenium import webdriver
 4 import os
 5 from selenium.webdriver.common.by import By
 6 from selenium.webdriver.common.action_chains import ActionChains  #引入ActionChains
 7 
 8 current = os.path.dirname(__file__)
 9 print(current)
10 chrome_driver_path = os.path.join(current,'../webdriver/chromedriver')
11 
12 driver = webdriver.Chrome(executable_path=chrome_driver_path)
13 driver.get('https://www.baidu.com')17 # element = driver.find_element(By.XPATH,'')
18 # mouse = ActionChains(driver)
19 # mouse.context_click().perform()#链条命令
20 
21 element = driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/div[3]/div/div/div[1]/a[2]/img')
22 ActionChains(driver).move_to_element(element).perform()#鼠标移动到一个元素上
23 time.sleep(2)
24 ActionChains(driver).context_click(element).perform()#右击
25 ActionChains(driver).double_click(element).perform()#双击
26 ActionChains(driver).drag_and_drop(element).perform()#拖动
27 ActionChains(driver).click_and_hold(element).pause(10).release(element).perform()#按下鼠标左键在一个元素上,按住暂停10s后再释放该元素

 

posted @ 2022-09-10 08:31  TesterWei  阅读(240)  评论(0编辑  收藏  举报