首页 > 技术文章 > python UI自动化之鼠标事件

FBGG 2020-11-20 16:11 原文

通过电脑屏幕坐标来操作鼠标:(不推荐使用)

  使用 pyautogui 模块:import pyautogui

1. 鼠标移动至:1629,875是电脑屏幕坐标;0.25是移动时间

  pyautogui.moveTo(1629,875, duration=0.25)

 

2. 点击鼠标左键、右键:同理,100,150是电脑屏幕坐标

  pyautogui.click(100,150,button='left')

  pyautogui.click(100,150,button='right')

 

3. 滚动鼠标:鼠标向上滚动200像素,负数即向下滚动

  pyautogui.scroll(200)

  pyautogui.scroll(-200)

 

鼠标操作

pywinauto. mouse

pywinauto操作鼠标,需要导入mouse模块,mouse模块中设置了一系列的鼠标操作事件

鼠标移动:move方法

move(coords=(x轴坐标,y轴坐标))

缓慢移动鼠标案例

for i in range(10):

x = 10 * i

y = 10 * i

time.sleep(0.5)

# 移动鼠标

mouse.move(coords=(x, y))

鼠标点击:click

# button指定左击还是右击,coords指定鼠标点击的位置

# 3.1、鼠标单击

# 指定位置,鼠标左击

mouse.click(button="left", coords=(40, 40))

# 指定位置 鼠标右击

# mouse.click(button="right", coords=(100, 200))

# 3.2 鼠标双击

mouse.double_click(button="left", coords=(140, 40))

# 4 按下鼠标:press

# 将属性移动到(140,40)坐标处按下

mouse.press(button="left", coords=(140, 40))

# 5 释放鼠标:repleace

# 将鼠标移动到(300,40)坐标处释放,

mouse.release(button="left", coords=(300, 40))

# 6、右键单击指定坐标

mouse.right_click(coords=(400, 400))

# 7、鼠标中键单击指定坐标(很少用的到)

mouse.wheel_click(coords=(400, 400))

# 8 滚动鼠标

# coords:指定鼠标的坐标位置。

# wheel_dist指定鼠标滚轮滑动的次数,正数往上,负数往下。

mouse.scroll(coords=(1200,300),wheel_dist=-3)

 

通过元素位置操作鼠标:(推荐使用)

下面我们来看一下ActionChains 提供了那些方法

  • click(on_element=None)                    #单击鼠标左键(该方式selenium中就有)
  • click_and_hold(on_element=None)     #点击鼠标左键,按住不放
  • context_click(on_element=None)           #点击鼠标右键
  • double_click(on_element=None)            #双击鼠标左键
  • drag_and_drop(source, target)              #拖拽到某个元素然后松开
  • drag_and_drop_by_offset(source, xoffset, yoffset)          #拖拽到某个坐标然后松开
  • move_by_offset(xoffset, yoffset)             #鼠标移动到距离当前位置(x,y)
  • move_to_element(to_element)               #鼠标移动到某个元素
  • move_to_element_with_offset(to_element, xoffset, yoffset) #将鼠标移动到距某个元素多少距离的位置
  • release(on_element=None)                     #在某个元素位置松开鼠标左键
  • perform()                                             #执行链中的所有动作

 

这些方法都该如何使用呢?

看如下代码

from selenium import webdriver
from selenium.webdriver import ActionChains
from time import sleep

wd=webdriver.Chrome()
wd.get("https://www.baidu.com/")

# 移动鼠标到某元素
element = wd.find_element("xpath", '//span[@class="soutu-btn"]')
ActionChains(wd).move_to_element(element).perform()

#点击鼠标左键,按住不放
element1 = wd.find_element("xpath", '//span[@class="soutu-btn"]')
ActionChains(wd).click_and_hold(element1).perform()

sleep(5)
quit()

 


参考文章:https://www.cnblogs.com/mengyu/p/6901489.html
参考文章:https://blog.csdn.net/weixin_39714015/article/details/112894796

推荐阅读