2022.4 2 pyautogui

参考资料:pyautogui的简单使用_风姿--惊鸿的博客-CSDN博客_pyautogui

详解Python中pyautogui库的最全使用方法_studyer_domi的博客-CSDN博客_pyautogui使用

python自动化操作PyAutogui库详解_~白+黑的博客-CSDN博客_pyautogui.click

【python--教程】pyautogui图​​​​​​形自动化,击败重复性办公任务。_猫先生的早茶的博客-CSDN博客_pyautogui教程

 PyAutoGUI帮助文档_qq_34053552的博客-CSDN博客_pyautogui 输入中文

Welcome to PyAutoGUI’s documentation! — PyAutoGUI documentation

1.安装

pip install pyautogui        #自动化
pip install opencv-python    #图像处理
pip install xlrd            #excel处理
pip install pyperclip        #复制粘贴

 为了使用方便,import pyautogui as ag

1.5

1.5是琐碎功能的汇总,可以先跳过,直接从2开始看

pyautogui.PAUSE = 1     #执行动作后暂停的秒数
#不设置则 执行动作后默认延迟时间是0.1秒
#只能在执行一些pyautogui动作后才能使用,建议用time.sleep
#最好在代码开始时就设置,否则无法使用ctrl c打断

#如果函数运行期间想要停止,请把鼠标移动到屏幕得左上角(0,0)位置,
#这触发pyautogui.FaailSafeException异常,从而终止程序运行。
pyautogui.FAILSAFE = True     #默认True则鼠标(0,0)可触发异常;False不触发

#坐标+RGB实时显示
pyautogui.displayMousePosition()    #官方自带的函数

#sleep,可用time.sleep()代替
pyautogui.sleep(time)

#获取中心点
pyautogui.center(coords)#coords is a 4-integer tuple of (left, top, width, height)
pyautogui.center((o,o,100,100))

#倒计时
pyautogui.countdown(seconds)
>>> ag.countdown(5)
5 4 3 2 1

#直接执行 pyautogui 在后台实际调用的命令
pyautogui.run(commandStr, _ssCount=None)
>>> ag.run('ccg-20,+0c')    这个命令表示
单击鼠标两次,然后鼠标光标向左移动20个像素,然后再次单击。
可忽略命令和参数之间的空白。命令字符必须是小写。引号必须是单引号。
>>> ag.run('c c g -20,+0 c')
'''
`c` => `click(button=PRIMARY)`
`l` => `click(button=LEFT)`
`m` => `click(button=MIDDLE)`
`r` => `click(button=RIGHT)`
`su` => `scroll(1) # scroll up`
`sd` => `scroll(-1) # scroll down`
`ss` => `screenshot('screenshot1.png') # filename number increases on its own`
`gX,Y` => `moveTo(X, Y)`
`g+X,-Y` => `move(X, Y) # The + or - prefix is the difference between move() and moveTo()`
`dX,Y` => `dragTo(X, Y)`
`d+X,-Y` => `drag(X, Y) # The + or - prefix is the difference between drag() and dragTo()`
`k'key'` => `press('key')`
`w'text'` => `write('text')`
`h'key,key,key'` => `hotkey(*'key,key,key'.replace(' ', '').split(','))`
`a'hello'` => `alert('hello')`
`sN` => `sleep(N) # N can be an int or float`
`pN` => `PAUSE = N # N can be an int or float`
`fN(commands)` => for i in range(N): run(commands)
'''

2. 鼠标的操作

x,y = pyautogui.position()    #当前鼠标的位置
x,y = pyautogui.size()        #当前屏幕分辨率

#判断坐标是否在屏幕内
pyautogui.onScreen(-1,-1)    #False
pyautogui.onScreen(1,1)        #True

#点击
pyautogui.click(x=None,y=None,clicks=1,interval=0.0,duration=0.0,button='primary')
#在xy位置单击,interval 单击之间等待的秒数,duration是从当前鼠标位置 移动到xy位置所用的时间
pyautogui.leftClick(x=None, y=None, interval=0.0, duration=0.0)
pyautogui.rightClick(x=None, y=None, interval=0.0, duration=0.0)
pyautogui.middleClick(x=None, y=None, interval=0.0, duration=0.0)    #中键单击
pyautogui.doubleClick(x=None, y=None, interval=0.0, button='left', duration=0.0,)
pyautogui.tripleClick(x=None, y=None, interval=0.0, button='left', duration=0.0,)

#拖动1
pyautogui.mouseDown(x=None, y=None, button='primary', duration=0.0,)    #移动到xy按下
pyautogui.mouseUp(x=None, y=None, button='primary', duration=0.0,)    #移动到xy松开

#拖动2
pyautogui.dragTo(x=None, y=None, duration=0.0, button='primary',  mouseDownUp=True)
pyautogui.dragRel(xOffset=0, yOffset=0, duration=0.0, button='primary', mouseDownUp=True)
#如果最后的参数mouseDownUp设置为False则鼠标只是单纯的移动,不执行按下或者松开操作!
#另外如果duration设置为0或者不设置,拖动也不会成功,只是单纯的移动!

#绝对移动,左上角坐标是(0,0)
#若duration小于pyautogui.MINIMUM_DURATION=0.1(默认),则移动是即时的
pyautogui.moveTo(x,y,duration=num_seconds)

#相对于当前位置移动,+x向右,+y向下
pyautogui.moveRel(xOffset,yOffset,duration=num_seconds)
pyautogui.move(x,y)

#滑轮滚动
pyautogui.scroll(-10) #向下10,且使用当前鼠标位置
pyautogui.scrolll(10,x=10,y=100) # 将鼠标移到x,y, 向上滚动10格

#进阶:用 缓动/渐变函数 控制光标移动的速度和方向
# PyAutoGUI有30种缓动/渐变函数,可以通过pyautogui.ease*?查看
# 开始很慢,不断加速
pyautogui.moveTo(100, 100, 2, pyautogui.easeInQuad)
# 开始很快,不断减速            pyautogui.easeOutQuad
# 开始和结束都快,中间比较慢    pyautogui.easeInOutQuad
# 一步一徘徊前进                pyautogui.easeInBounce
# 徘徊幅度更大,甚至超过起点和终点    pyautogui.easeInElastic

3. 键盘功能

#模仿键盘输入
pyautogui.typewrite(message, interval=0.0,)
pyautogui.write('hello world',interval=0.25)
#typewrite和write都可以,但都不能写中文(要写中文暂时只能用paperclip.copy()来复制)
#https://github.com/asweigart/pyautogui/issues/237

#查看可用的按键的名称
>>> pyautogui.KEYBOARD_KEYS

#按单个键 并松开
pyautogui.press(keys, presses=1, interval=0.0)
pyautogui.press('enter') #按下并释放enter
pyautogui.press(['left','left','left'])
pyautogui.press('left',presses=3)
pyautogui.keyDown('shift') # 按下`shift`键
pyautogui.keyUp('shift') # 松开`shift`键

#按两个键
with pyautogui.hold('shift'):
	pyautogui.press(['left','left','left'])
# 相当于先按住shift,再按三次left,再释放shift

#按多个键    为了方便按下热键或键盘快捷键,
#可以传递几个按键字符串,其按顺序按下,以相反顺序释放
pyautogui.hotkey('ctrl','shift','esc')
# 相当于先按下ctrl,shift,esc,再逐个释放esc,shift,ctrl
# interval可用

在这里插入图片描述

4.消息框

pyautogui利用PyMsgBox中的消息框函数来提供一种跨平台的纯Python方式来显示JavaScript样式的消息框

pyautogui.alert(text='',title='',button='OK')    #点击返回button的文本
pyautogui.confirm(text='',title='',buttons=['OK','Cancel'])    #点击返回对应项的文本
pyautogui.prompt(text='',title='',default='')    #单击取消返回None
pyautogui.password(text='',title='',default='',mask='*')
#键入的字符显示为*,返回输入文本,取消返回None

5.截图定位

这些功能由PyScreez模块提供,该模块与pyautogui一起安装

screenshot()# 返回一个Image对象,消耗100微秒
# 全屏
img1=pyautogui.screenshot('abc.png')    #保存在当前目录下
# 区域:起始坐标x,y及宽高
img2=pyautogui.screenshot('abc2.png',region=(0,0,300,400))

#100%匹配: 匹配图像abc2.png  在当前屏幕相同画面的位置:起始坐标x,y及宽高
#如果当前屏幕没有匹配的画面,则返回None
>>> a=ag.locateOnScreen('abc2.png')
>>> print(a)
Box(left=0, top=0, width=300, height=400)
#获取图像截取位置中心
>>> x,y=ag.locateCenterOnScreen('abc2.png')
>>> print(x,y)
150 200
#换一个屏幕页面,使当前页面没有截图abc2.png的内容
>>> a=ag.locateOnScreen('abc2.png')
>>> print(a)
None

#灰度匹配:上面的匹配是100%匹配,灰度匹配则是
#通过grayscale=True增加灰度(即降低图像与屏幕的颜色饱和度)
#去进行匹配,可能会导致匹配错误(如灰色的图片 匹配到 彩色的屏幕)
#但可以加速匹配过程(大约30%左右)
>>> a=ag.locateOnScreen('abc2.png',grayscale=True)
>>> print(a)
Box(left=0, top=0, width=300, height=400)
#可能会出现100%能匹配 而 灰度不能匹配的情况

#上述匹配都只会返回符合条件的第一个对象
#要匹配所有符合项,可用for 和 locateAllOnScreen
for pos in pyautogui.locateAllOnScreen('abc2.png'):
  print(pos)
#or
print(list(pyautogui.locateAllOnScreen('abc2.png')))

#匹配第一张图片在第二张图片里的坐标(注意是图片不是屏幕)
>>> ag.locate('s.png','f.png',grayscale=False)
Box(left=137, top=107, width=37, height=34)    #返回匹配到的第一个

#匹配第一张图片在第二张图片里的所有坐标
>>> list(ag.locateAll('s2.png','f.png',grayscale=False))
[Box(left=121, top=78, width=17, height=22), 
Box(left=121, top=114, width=17, height=22)]    #返回匹配到的所有


#获取屏幕截图中 像素点 的RGB颜色:
img=pyautogui.screenshot()
img.getpixel((100,200))
# 或直接
pyautogui.pixel(100,200)

>>> print(ag.position())    #import pyautogui as ag
Point(x=1550, y=583)
>>> img.getpixel((1550,583))
(39, 46, 57)
# 验证单个像素是否与给定的像素匹配
>>> ag.pixelMatchesColor(1550,583,(39, 46, 57))
True
# 用tolerance指定RGB的误差允许范围
>>> ag.pixelMatchesColor(1550,583,(39, 46, 46),tolerance=10)
False
>>> ag.pixelMatchesColor(1550,583,(39, 46, 47),tolerance=10)
True

 pyautogui的图片定位常会出现定位不到的情况(比较鸡肋),除了用上述的灰度匹配,还可以加confidence进行 模糊匹配(减低识别精度)。需要先安装opencv包

'''
The optional `confidence` keyword argument specifies the accuracy with which the function 
should locate the image on screen. This is helpful in case the function is not able to 
locate an image due to negligible pixel differences:
'''
>>> import pyautogui
>>> button7location = pyautogui.locateOnScreen('calc7key.png', confidence=0.9)
>>> button7location
Box(left=1416, top=562, width=50, height=41)

6.窗口

官方文档

是找不到下述API的,原因是PyGetWindow currently only supports Windows

#返回所有已打开窗口的对象
>>> pyautogui.getAllWindows()
[Win32Window(hWnd=65690),....
#返回包含 点(x,y)的窗口对象的列表
>>> pyautogui.getWindowsAt(x, y)
getActiveWindow()        #返回当前活动窗口对象
getActiveWindowTitle()    #返回当前活动对象的窗口标题
getAllTitles()            #返回所有的窗口标题
getWindowsWithTitle(title)    #根据标题找窗口,返回窗口对象

pyautogui库帮助文档的获取鼠标位置颜色的范例,也就是displayMousePosition()的源码

import pyautogui

print('Press Ctrl-C to quit.')
try:
  while True:
    # Get and print the mouse coordinates.
    x, y = pyautogui.position()
    positionStr = 'X:' + str(x).rjust(4) + ' Y:' + str(y).rjust(4)
    pix = pyautogui.screenshot().getpixel((x, y)) # 获取鼠标所在屏幕点的RGB颜色
    positionStr += ' RGB:(' + str(pix[0]).rjust(3) + ',' + str(pix[1]).rjust(3) + ',' + str(pix[2]).rjust(3) + ')'
    print(positionStr, end='') # end='' 替换了默认的换行
    print('\b' * len(positionStr), end='', flush=True) # 连续退格键并刷新,删除之前打印的坐标,就像直接更新坐标效果
except KeyboardInterrupt: # 处理 Ctrl-C 按键
  print('\nDone.')

拖选文本 并 复制:

import pyautogui as ag
import time

ag.mouseDown()
ag.moveRel(100,0)
ag.mouseUp()
time.sleep(0.25)
ag.hotkey('ctrl','c')

#dragTo可以用了,必须要设置duration不为0,才能生效

复制参数:

import pyperclip
import pyautogui

def paste(foo):
    pyperclip.copy(foo)
    pyautogui.hotkey('ctrl', 'v')
 
foo = '学而时习之'

pyautogui.click(130,30)    #鼠标移动至要粘贴的地方
paste(foo)

其他案例:Welcome to PyAutoGUI’s documentation! — PyAutoGUI documentation

import pyautogui

pyautogui.PAUSE = 0.5    #不设置会导致ctrl c无法生效
try:
    distance = 200
    while distance > 0:
        pyautogui.dragRel(distance, 0, duration=0.5) # 向右
        distance -= 5
        pyautogui.dragRel(0, distance, duration=0.5) # 向下
        pyautogui.dragRel(-distance, 0, duration=0.5) # 向左
        distance -= 5
        pyautogui.dragRel(0, -distance, duration=0.5) # 向上
except KeyboardInterrupt:
  print('\nDone.')

 用excel进行批处理:pyautogui的简单使用_风姿--惊鸿的博客-CSDN博客_pyautogui

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值