1.安装

  1. Windows安装
    1. 自动化

      pip install pyautogui
      
    2. 图像处理

      pip install opencv-python
      
    3. excel处理

      pip install xlrd
      
    4. 复制粘贴

      pip install pyperclip
      

2. 鼠标的操作

  1. 当前鼠标的位置

    pyautogui.position()
    
  2. 当前屏幕分辨率

    pyautogui.size()
    
  3. 判断坐标是否在屏幕内

    pyautogui.onScreen(x,y)
    
  4. 鼠标移动,左上角坐标位(0,0),x向右增加,y向下增加.若durations小于pyautogui.MINIMUM_DURATION=0.1移动是即时的,

    pyautogui.moveTo(x,y,duration=num_seconds)
    
  5. 相对于当前位置移动鼠标

    pyautogui.moveRel(xOffset,yOffset,duration=num_seconds)
    pyautogui.move(x,y)
    
  6. 鼠标拖动,dragTo()与drag()与moveTo()和move()类似,button决定按哪个键拖动

    pyautogui.dragTo(x,y,button='left')#左键拖动
    
  7. 鼠标点击

    pyautogui.click()#当前位置单击
    pyautogui.click(x=moveTox,y=moveToy,clicks=num_of_clicks,interval=secs_clicks,button='left')
    #interval 单击之间等待的秒数
    #doubleClick() 执行鼠标双击
    #right/left/middle/Click() 右击/左击/中间单击
    #mouseDown()/mouseUp() 鼠标按下/释放,可进行鼠标拖动
    
  8. 鼠标滚动

    pyauotgui.scroll(10) #向上滚动10格
    pyautogui.scroll(-10) #向下,,,
    pyautogui.scrolll(10,x=10,y=100) # 将鼠标移到x,y,在向上滚动10格
    # OS X和Linux平台上,可以通过和scroll()执行水平滚动
    

3. 键盘功能

  1. write()函数

    pyautogui.write('hello world',interval=0.25) # 打印书hellow world 每个字符后延迟0.25秒
    
  2. press()

    #keyDown(),keyUp()
    # press实现一个键按下与释放
    pyautogui.press('enter') #按下并释放enter
    pyautogui.press(['left','left','left'])
    pyautogui.press('left',presses=3)
    # 要在每次按下之间加延迟,interval int/float
    
  3. hold() 上下文管理器

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

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

4.消息框

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

  1. alert()

    pyautogui.alert(text='',title='',button='OK') # 显示一个带有文本和确定按钮的简单消息框,用户点击返回button的文本
    
  2. confirm()

    pyautogui.confirm(text='',title='',buttons=['OK','Cancel']) #显示带有确定和取消按钮的消息框,可以自定义按钮的数量和文本,点击返回按钮的文本
    
  3. prompt()

    pyautogui.prompt(text='',title='','default='') # 显示文本输入和确定/取消按钮,确定返回输入的文本,单击取消返回None
    
  4. password()

    pyautogui.password(text='',titile='',default='',mask='*') # 显示文本输入和确认/取消按钮,键入的字符显示为*,返回输入文本,取消返回None
    

5.截图定位

pyautogui可以截取屏幕截图,并将之保存在文件中,,并在屏幕中定位图像。这些功能由PyScreez模块提供,该模块与pyautogui一起安装
屏幕截图功能需要安装(windows)

pip install Pillow
  1. screenshot()

    screenshot()# 返回一个Image对象,传递文件名字符串会将屏幕截图保存在文件中,并将其作为Image对象返回
    # 全屏
    img1=pyautogui.screenshot('文件名.png')
    # 区域
    img2=pyautogui.screenshot(region=(0,0,300,400))# 上下宽高捕获
    
  2. 定位函数

    # localOnScreen('文件名.png')获取图像所在位置,返回的是一个整数组元组:(左,上,宽,高),可以传递此元组center()以获取该区域中心x,y坐标,找不到会ImageNotFoundException
    # confidence参数 指定位精度,,需要安装OpenCV才起作用
    # localCenterOnScreen() #结合了localOnScreen()与center()
    x,y=pyautogui.localCenterOnScreen('文件名.png')
    pyautogui.click(x,y)
    
  3. 灰度匹配

    # 通过grayscale=True给定位函数增加灰度,可以稍微加速(大约30%左右),会降低图像与屏幕的颜色饱和度,加快定位,但可能会导致匹配错误
    loc=pyautogui.localOnScreen('文件名.png',grayscale=True)
    
  4. 像素匹配

    # 获取屏幕截图中像素的RGB颜色:
    img=pyautogui.screenshot()
    img.getpixel((100,200))
    # 或
    pyautogui.pixel(100,200) #(130,135,144)
    # 验证单个像素是否与给定的像素匹配
    pyautogui.pixelMatchesColor(100,200,(130,135,144)) # True
    # 可以使用tolerance指定红绿蓝在匹配的情况下可以变化多少
    pyautogui.pixelMatchesCoor(100,200,(140,125,134),tolerance=10) #True
    

6.小试

通过excel中的命令流程,自动打开浏览器,百度python,再关闭浏览器,再打开桌面备忘录,将excel中的文本输入到备忘录,并保存退出

#导入 用于自动化控制鼠标与键盘
import pyautogui
# 用于时间处理
import time
#用于读取excel中的操作指令
import xlrd
#导入粘贴复制模块
import pyperclip

#定义鼠标事件

#pyautogui库其他用法 https://blog.csdn.net/qingfengxd1/article/details/108270159
#定义鼠标操作方法
def mouseClick(clickTimes,lOrR,img,reTry):
    if reTry == 1:
        while True:
            #获取应用程序位置
            location=pyautogui.locateCenterOnScreen(img,confidence=0.9)
            if location is not None:
                # interval 单击之间等待的秒数
                #x,y是鼠标坐标,
                #duration为执行此次动作的设置时间,0为立即执行
                #button有几个默认选项,left,middle,right,primary,secondary 默认为左键模式,后两者组合就是拖动
                #拖动语句:
                # pyautogui.dragTo(x=None, y=None, duration=0.0, button='primary', mouseDownUp=True)
                # mouseDownUp设置为False则鼠标只是单纯的移动,不会按下与松开 duration设置为0或不设置也不行
                pyautogui.click(location.x,location.y,clicks=clickTimes,interval=0.2,duration=0.2,button=lOrR)
                break
            print("未找到匹配图片,0.1秒后重试")
            time.sleep(0.1)
    elif reTry == -1:
        while True:
            # confidence 查找图片精确度,默认为 1
            location=pyautogui.locateCenterOnScreen(img,confidence=0.9)
            if location is not None:
                pyautogui.click(location.x,location.y,clicks=clickTimes,interval=0.2,duration=0.2,button=lOrR)
            time.sleep(0.1)
    elif reTry > 1:
        i = 1
        while i < reTry + 1:
            location=pyautogui.locateCenterOnScreen(img,confidence=0.9)
            if location is not None:
                pyautogui.click(location.x,location.y,clicks=clickTimes,interval=0.2,duration=0.2,button=lOrR)
                print("重复")
                i += 1
            time.sleep(0.1)




# 数据检查
# cmdType.value  1.0 左键单击    2.0 左键双击  3.0 右键单击  4.0 输入  5.0 等待  6.0 滚轮
# ctype     空:0
#           字符串:1
#           数字:2
#           日期:3
#           布尔:4
#           error:5
def dataCheck(sheet1):
    checkCmd = True
    #行数检查
    if sheet1.nrows<2:
        print("没数据啊哥")
        checkCmd = False
    #每行数据检查
    i = 1
    while i < sheet1.nrows:
        # 第1列 操作类型检查
        cmdType = sheet1.row(i)[0]
        #非数字 不正常操作
        if cmdType.ctype != 2 or (cmdType.value != 1.0 and cmdType.value != 2.0 and cmdType.value != 3.0 
        and cmdType.value != 4.0 and cmdType.value != 5.0 and cmdType.value != 6.0):
            print('第',i+1,"行,第1列数据有毛病")
            checkCmd = False
        # 第2列 内容检查
        cmdValue = sheet1.row(i)[1]
        # 读图点击类型指令,内容必须为字符串类型
        #字符串 左键双击或右键单击
        if cmdType.value ==1.0 or cmdType.value == 2.0 or cmdType.value == 3.0:
            if cmdValue.ctype != 1:# 非字符串
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        # 输入类型,内容不能为空
        if cmdType.value == 4.0:
            #为空
            if cmdValue.ctype == 0:
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        # 等待类型,内容必须为数字
        #等待
        if cmdType.value == 5.0:
            #为数字
            if cmdValue.ctype != 2:
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        # 滚轮事件,内容必须为数字
        #滚轮
        if cmdType.value == 6.0:
            #非数字
            if cmdValue.ctype != 2:
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        i += 1
    return checkCmd

#任务
def mainWork(img):
    i = 1
    while i < sheet1.nrows:
        #取本行指令的操作类型
        cmdType = sheet1.row(i)[0]
        #左键单击
        if cmdType.value == 1.0:
            #取图片名称
            img = sheet1.row(i)[1].value
            print('图片名称:',img)
            #默认执行一次
            reTry = 1
            #第三列 内容为数字 且不为空
            if sheet1.row(i)[2].ctype == 2 and sheet1.row(i)[2].value != 0:
                #执行第三列值次
                reTry = sheet1.row(i)[2].value
            mouseClick(1,"left",img,reTry)
            print("单击左键",img)
        #2代表双击左键
        elif cmdType.value == 2.0:
            #取图片名称
            img = sheet1.row(i)[1].value
            #取重试次数
            reTry = 1
            #重复执行第三列值次
            if sheet1.row(i)[2].ctype == 2 and sheet1.row(i)[2].value != 0:
                reTry = sheet1.row(i)[2].value
            mouseClick(2,"left",img,reTry)
            print("双击左键",img)
        #3代表右键
        elif cmdType.value == 3.0:
            #取图片名称
            img = sheet1.row(i)[1].value
            #取重试次数
            reTry = 1
            if sheet1.row(i)[2].ctype == 2 and sheet1.row(i)[2].value != 0:
                reTry = sheet1.row(i)[2].value
            mouseClick(1,"right",img,reTry)
            print("右键",img) 
        #4代表输入
        elif cmdType.value == 4.0:
            inputValue = sheet1.row(i)[1].value
            #复制输入的内容
            pyperclip.copy(inputValue)
            #按顺序对传递的参数执行按键,然后按相反顺序执行按键释放
            pyautogui.hotkey('ctrl','v')
            #回车
            pyautogui.hotkey('enter')
            time.sleep(0.5)
            print("输入:",inputValue)                                        
        #5代表等待
        elif cmdType.value == 5.0:
            #取等待的秒数
            waitTime = sheet1.row(i)[1].value
            time.sleep(waitTime)
            print("等待",waitTime,"秒")
        #6代表滚轮
        elif cmdType.value == 6.0:
            #取图片名称
            scroll = sheet1.row(i)[1].value
            # scroll(clicks, x=None, y=None, logScreenshot=None, _pause=True):
            #执行鼠标滚轮操作,是垂直还是水平取决于底层操作系统
            #x,y说明鼠标事件发生的位置,若没有,则使用当前鼠标位置,若是悬浮值,
            # 则四舍五入,如果超出屏幕边界,则事件发生在屏幕边缘
            # 点击(int,float):要执行的滚动量。x(int,float,None,tuple,可选):屏幕上发生单击的x位置。默认情况下没有。如果是tuple,则用于x和y.y(int,float,None,可选):屏幕上发生单击的y位置。默认情况下没有
            pyautogui.scroll(int(scroll))
            print("滚轮滑动",int(scroll),"距离")                      
        i += 1

if __name__ == '__main__':
    file = r'C:\Users\lenovo\Desktop\waterRPA\cmde.xls'
    #打开文件
    wb = xlrd.open_workbook(filename=file)
    #通过索引获取表格sheet页
    sheet1 = wb.sheet_by_index(0)
    print('欢迎来到wph的RPA~')
    #数据检查
    checkCmd = dataCheck(sheet1)
    if checkCmd:
        key=input('选择功能: 1.做一次 2.循环到死 3.退出\n')
        if key=='1':
            #循环拿出每一行指令
            mainWork(sheet1)
        elif key=='2':
            while True:
                mainWork(sheet1)
                time.sleep(0.1)
                print("等待0.1秒")
        elif key=='3':
            exit()
    else:
        print('输入有误或者已经退出!')

  1. 定位图片在这里插入图片描述
  2. excel命令流程在这里插入图片描述



  • 时间一分,贵如千金
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐