一,PyAutoGui介绍

        PyAutoGUI是Python功能强大的UI自动化库,其目的是可以用程序自动控制鼠标和键盘操作,主要用来实现PC端的UI自动化。

        ①有鼠标控制、键盘操作、屏幕截图、图片定位、消息对话框、窗口操作等功能;  
        ②有倒计时、鼠标坐标颜色抓取小程序、UI自动化迷你语言等实用工具;  
        ③有故障安全、通用暂停等机制。  

二,PyAutoGui安装

cmd安装命令:

pip install PyAutoGUI

如果因为python或者pip版本安装失败,以下提供一种解决办法:

        1.进入网址:https://pypi.org/project/PyAutoGUI/#files

        2.下载PyAutoGui后缀为tar.gz的压缩包

        3.在解压目录上输出cmd,回车

        4.输入命令:python setup.py install

,PyAutoGui图片定位常用三种方式

       1, locateOnScreen()定位图片整体位置

print(locateOnScreen('images/test.png'))
print(type(locateOnScreen('images/test.png')))

>>Box(left=812, top=1042, width=35, height=30)
>><class 'pyscreeze.Box'>

        locateOnScreen定位图片,会返回一个pyscreeze.Box(left,top,width,height),left和top是图片左上角的坐标,width和height是图片的宽和高。

        2, center()返回locateOnScreen获取图片整体位置的中心点

img = locateOnScreen('images/test.png')
Center = center(img)
print(Center)
print(type(Center))
print(Center.x,Center.y)

>>Point(x=872, y=1058)
>><class 'pyscreeze.Point'>
>>872 1058

        center可以根据locateOnScreen定位图片的位置,会返回一个pyscreeze.Point格式的图片中心左边点Point(x=test1,y=test2),可以通过Point().x 来获取Point中x的值,也可以通过Point().y 来获取Point中y的值。

        3locateCenterOnScreen()定位图片的中心点

print(locateCenterOnScreen('images/test1.png'))
print(type(locateCenterOnScreen('images/test1.png')))

>>Point(x=872, y=1058)
>><class 'pyscreeze.Point'>

        locateCenterOnScreen()相当于是locateOnScreen()和center()的结合。 返回值也和center()的返回值一样。

,locateOnScreen+center和locateCenterOnScreen定位速度比较

start = time.perf_counter()
locateCenterOnScreen('images/test1.png')
print('locateCenterOnScreen()所用时间为{}:'.format((time.perf_counter())-start))

>>locateCenterOnScreen()所用时间为:0.17265509999999998

start = time.perf_counter()
center(locateOnScreen('images/test1.png'))
print('center+locateCenterOnScreen所用时间为:{}'.format((time.perf_counter())-start))

>>center+locateCenterOnScreen所用时间为:0.16086670000000003

        由此可见locateOnScreen+center的运行速度是快于locateCenterOnScreen的,毕竟locateCenterOnScreen是由locateOnScreen+center封装得来,如果在实际项目中需要结合实际场景来进行再次封装,建议采用locateOnScreen+center的定位方式。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐