前言

本文分为代码篇和实操篇,代码篇以“不高兴就喝水”的代码为原版和其他改版做对比,帮助学习了解。实操部分也分为原版的实操和改版的实操。

学前准备:
pyautogui库用法:https://blog.csdn.net/qingfengxd1/article/details/108270159

代码

原版

来自作者“不高兴就喝水”,用到python的两个库和三个方法

import pyautogui
import time
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:
                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:
            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
            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')
            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
            pyautogui.scroll(int(scroll))
            print("滚轮滑动",int(scroll),"距离")                      
        i += 1

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

第一部分:环境库

import pyautogui
import time
import xlrd
import pyperclip

安装依赖包:
方法:windows系统在cmd中(win+R 输入cmd 回车)输入
pip install pyperclip 回车
pip install xlrd 回车
pip install pyautogui==0.9.50 回车
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple 回车
pip install pillow 回车

第二部分:定义鼠标事件

#定义鼠标事件
#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:
                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:
            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)

解读:
1、

用到python的两个库和三个方法,其中,第一个库,pyautogui,用该方法进行定位,我们传进去截图,它就会把截图所对应的区域在屏幕中的位置返回回来。我们把图标对应的截图传进去,只要你这个图标在屏幕上出现了,它就会把对应的位置返回回来。

2、核心代码

pyautogui.click(location.x,location.y,clicks=clickTimes,interval=0.2,duration=0.2,button=lOrR)
解读
1、pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks, button='left')
# 其中,clicks是点击次数
# button属性可以设置成left,middle和right;
# interval是点击时间间隔;

2、pyautogui.click() # 鼠标当前位置点击一下

3、pyautogui.click(x=100, y=200, duration=2) # 先移动到(100, 200)再单击


有了位置之后,再把这个位置传给pyautogui提供的操作鼠标和键盘的方法,来进行对应的左键,右键以及输入等操作。

第三部分:数据检查

# 数据检查
# 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
            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')
            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
            pyautogui.scroll(int(scroll))
            print("滚轮滑动",int(scroll),"距离")                      
        i += 1

解读
1、由于双击功能存在问题,故针对该部分的配置进行学习
首先,在任务部分,定义了变量reTry

从cmd表中读取2

接着,赋值给到鼠标事件的代码


怀疑是3.9的bug

结果不是,是360这软件的坑,退出就可以执行了,真的是调试有问题,先删360。。。。

第五部分:主程序

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

解读:
1、


用到的第二个库xlrd,是用来读取excel,对excel里面的指令类别和图片名称进行读取。

改版

cmd.xls里增加三个指令:
7热键组合,8本机时间粘贴,9系统命令集(理论上windows和Linxu都可以使用)

热键组合:
解决了原版中无法使用快捷键和键盘录入的问题,命令中的4输入指令,实际为复制粘贴,会占用粘贴板资源。如果你先复制了一个文件,然后在用4指令打开路径,粘贴板中原来复制的文件就会被刚刚的路径所覆盖。

第一列填写7,第二列将需要的组合的热键以英文半角逗号(”,”)分隔填写即可。
例如:win,r ctrl,shift,esc 1,2,3,4,del
当然单个的按键也是可以,单个数按键后面必须加”,” (例如:9, 按一下9这个键。)
热键的名称请查询第一页最后pyautogui库的用法。

注意:英文中的”,”无法被识别,原因是这个符号被用来分隔其他按键组合了。

本机时间粘贴:
解决了某些时候,需要获取当前系统时间的困恼。此指令也会使用粘贴板,实际为复制粘贴。
比如:自动备份文件后重命名需要是当前系统时间。

第一列填写8,第二列其实可以填写任何东西(但是一定要填写,否者不执行),第三列重复次数无效。
为了后期维护方便,建议大家都写:当前时间

系统命令集:
调用本系统的命令集,扩展了应用可能性,用批处理写的东西也可以调用了。
理论上windows和Linxu都可以使用,windows是CMD,Linxu应该是command mode

第一列填写9,第二列填写系统指令,第三列重复次数无效。
例如:
start c: (在新窗口中打开C盘)
start cmd (在新窗口中打开CMD程序)

本指令使用了os.system 这个方法。有兴趣的大家可以查一下。

对于主程序,作了以下改进:

1、增加了多次循环的选项,可以输入循环次数。

2、增加了退出程序选项,大家尽量使用这个选项退出程序。
可以避免出现exe执行文件产生大量临时文件,占满C盘。

3、优化了控制台的显示,并增加一个清理屏幕显示的功能,更加清晰的看到每一步的执行。

import pyautogui
import time
import xlrd
import pyperclip
import time
import os


#定义鼠标事件

#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:
                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:
            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)


#定义热键事件
![](../../waterRPA/shu.png)
#hotkey_get方法用来判断热键组合个数,还是文字输入。此方法由B站up主 尔茄无双 提供。
def hotkey_get(hk_g_inputValue):
    try:
        newinput = hk_g_inputValue.split(',')
        pyautogui.hotkey(*tuple(newinput))
    except:
        pyperclip.copy(hk_g_inputValue)
        pyautogui.hotkey('ctrl', 'v')

#hotkey_get方法用来判断热键组合个数,并把热键传到对应的变量上newinput[0],[1],[2],[3]……[9]只写了10个后续可以添加。【老方法弃用】
    # newinput = hk_g_inputValue.split(',')
    #         if len(newinput)==1: 
    #        			 pyautogui.hotkey(hk_g_inputValue)
    #         elif len(newinput)==2:
    #        			 pyautogui.hotkey(newinput[0],newinput[1])
    #         elif len(newinput)==3:
    #        			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2])
    #         elif len(newinput)==4:
    #        			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3])
    #         elif len(newinput)==4:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3])
    #         elif len(newinput)==5:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4])
    #         elif len(newinput)==6:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5])
    #         elif len(newinput)==7:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6])       
    #         elif len(newinput)==8:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6],newinput[7])     
    #         elif len(newinput)==9:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6],newinput[7],newinput[8])
    #         elif len(newinput)==10:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6],newinput[7],newinput[8],newinput[9])   
                                                                                                                                                         
#hotkey_Group方法调用hotkey_get方法,并判断其热键内容是否需要循环。
def hotkeyGroup(reTry,hkg_inputValue):
    if reTry == 1:
            hotkey_get(hkg_inputValue)                  
            print("执行了:",hkg_inputValue)
            time.sleep(0.1)
    elif reTry == -1:
        while True:
            hotkey_get(hkg_inputValue)
            print("执行了:",hkg_inputValue)
            time.sleep(0.1)
    elif reTry > 1:
        i = 1
        while i < reTry + 1:
                hotkey_get(hkg_inputValue)
                print("执行了:",hkg_inputValue)
                i += 1
                time.sleep(0.1)



# 数据检查
# cmdType.value  1.0 左键单击    2.0 左键双击  3.0 右键单击  4.0 输入  5.0 等待  6.0 滚轮  
# 7.0 热键组合(最多4个)
# 8.0 粘贴当前时间
# 9.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 
        and cmdType.value != 7.0 and cmdType.value != 8.0 and cmdType.value != 9.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
        # 7.0 热键组合,内容不能为空
        if cmdType.value == 7.0:
            if cmdValue.ctype == 0:
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        # 8.0 时间,内容不能为空
        if cmdType.value == 8.0:
            if cmdValue.ctype == 0:
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        # 9.0 系统命令集模式,内容不能为空
        if cmdType.value == 9.0:
            if cmdValue.ctype == 0:
                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
            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')
            print("输入:",inputValue) 
            time.sleep(0.5)                                       
        #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
            pyautogui.scroll(int(scroll))
            print("滚轮滑动",int(scroll),"距离")     
       #7代表_热键组合
        elif cmdType.value == 7.0:
            #取重试次数,并循环。
            reTry = 1
            if sheet1.row(i)[2].ctype == 2 and sheet1.row(i)[2].value != 0:
                reTry = sheet1.row(i)[2].value
            inputValue = sheet1.row(i)[1].value
            hotkeyGroup(reTry,inputValue)
            time.sleep(0.5)
       #8代表_粘贴当前时间
        elif cmdType.value == 8.0:      
            #设置本机当前时间。
            localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
            pyperclip.copy(localtime)
            pyautogui.hotkey('ctrl','v')
            print("粘贴了本机时间:",localtime)
            time.sleep(0.5)
       #9代表_系统命令集模式
        elif cmdType.value == 9.0:      
            wincmd = sheet1.row(i)[1].value
            os.system(wincmd)
            print("运行系统命令:",wincmd)
            time.sleep(0.5) 
        i += 1

#主程序
while True:
    if __name__ == '__main__':
        file = 'cmd.xls'
        #打开文件
        wb = xlrd.open_workbook(filename=file)
        #通过索引获取表格sheet页
        sheet1 = wb.sheet_by_index(0)
        print('欢迎使用不高兴就喝水牌RPA~')
        print('大羽改良版_v211207')
        print('')
        #避免多次循环导致的ctrl+v导入到,按ESC进行取消。
        pyautogui.hotkey('esc')
        #数据检查
        checkCmd = dataCheck(sheet1)

        #输入选项实现功能
        if checkCmd:
            key=input('选择功能: 1.做一次 2.循环几次 3.循环到死 0.退出程序\n特殊功能:c.清理屏幕显示\n———————————————————————————————————————\n')
            if key=='1':
                #循环拿出每一行指令 
                print("正在执行第1次命令")  
                print("")
                mainWork(sheet1)
                print("")
                print("已经完成第1次命令")  
                print("——————————————————分割线——————————————————")  
                print("")

            elif key=='2':
                print("")
                count=0
                times=input('输入需要循环的次数,务必输入正整数。\n')
                times=int(times)
                if count < times:
                    while count < times:
                            count+=1 
                            print("正在执行第",count,"次","命令")
                            print("")
                            mainWork(sheet1)
                            time.sleep(0.1)
                            print("等待0.1秒") 
                            print("") 
                            print("已经完成第",count,"次","命令") 
                            print("——————————————————分割线——————————————————")  
                            print("") 
                else:
                    print('输入有误或者已经退出!')
                    os.system('pause')
                    print("") 
                    print("——————————————————————————————————————————")  

            elif key=='3':
                count=0
                while True:
                    count+=1
                    print("正在执行第",count,"次","命令")
                    print("")
                    mainWork(sheet1)
                    time.sleep(0.1)
                    print("等待0.1秒")  
                    print("")
                    print("已经完成第",count,"次","命令")  
                    print("——————————————————分割线——————————————————")  
                    print("")  

            elif key=='0':
                print("正清理缓存文件...")
                os.system('@echo off & for /d %i in (%temp%\^_MEI*) do (rd /s /q "%i")>nul')
                exit("正在退出程序...")
                
            elif key=='c':
                os.system('cls')
                
            else:
                print('输入有误或者已经退出!')
                os.system('pause')
                print("") 
                print("——————————————————————————————————————————")  

第一部分:环境库

import pyautogui
import time
import xlrd
import pyperclip
import time
import os

第二部分:定义鼠标事件

#定义鼠标事件

#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:
                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:
            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)


第三部分:定义热键事件

#定义热键事件
![](../../waterRPA/shu.png)
#hotkey_get方法用来判断热键组合个数,还是文字输入。此方法由B站up主 尔茄无双 提供。
def hotkey_get(hk_g_inputValue):
    try:
        newinput = hk_g_inputValue.split(',')
        pyautogui.hotkey(*tuple(newinput))
    except:
        pyperclip.copy(hk_g_inputValue)
        pyautogui.hotkey('ctrl', 'v')

#hotkey_get方法用来判断热键组合个数,并把热键传到对应的变量上newinput[0],[1],[2],[3]……[9]只写了10个后续可以添加。【老方法弃用】
    # newinput = hk_g_inputValue.split(',')
    #         if len(newinput)==1: 
    #        			 pyautogui.hotkey(hk_g_inputValue)
    #         elif len(newinput)==2:
    #        			 pyautogui.hotkey(newinput[0],newinput[1])
    #         elif len(newinput)==3:
    #        			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2])
    #         elif len(newinput)==4:
    #        			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3])
    #         elif len(newinput)==4:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3])
    #         elif len(newinput)==5:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4])
    #         elif len(newinput)==6:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5])
    #         elif len(newinput)==7:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6])       
    #         elif len(newinput)==8:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6],newinput[7])     
    #         elif len(newinput)==9:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6],newinput[7],newinput[8])
    #         elif len(newinput)==10:
    #            			 pyautogui.hotkey(newinput[0],newinput[1],newinput[2],newinput[3],newinput[4],newinput[5],newinput[6],newinput[7],newinput[8],newinput[9])   
                                                                                                                                                         
#hotkey_Group方法调用hotkey_get方法,并判断其热键内容是否需要循环。
def hotkeyGroup(reTry,hkg_inputValue):
    if reTry == 1:
            hotkey_get(hkg_inputValue)                  
            print("执行了:",hkg_inputValue)
            time.sleep(0.1)
    elif reTry == -1:
        while True:
            hotkey_get(hkg_inputValue)
            print("执行了:",hkg_inputValue)
            time.sleep(0.1)
    elif reTry > 1:
        i = 1
        while i < reTry + 1:
                hotkey_get(hkg_inputValue)
                print("执行了:",hkg_inputValue)
                i += 1
                time.sleep(0.1)



第四部分:数据检查

# 数据检查
# cmdType.value  1.0 左键单击    2.0 左键双击  3.0 右键单击  4.0 输入  5.0 等待  6.0 滚轮  
# 7.0 热键组合(最多4个)
# 8.0 粘贴当前时间
# 9.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 
        and cmdType.value != 7.0 and cmdType.value != 8.0 and cmdType.value != 9.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
        # 7.0 热键组合,内容不能为空
        if cmdType.value == 7.0:
            if cmdValue.ctype == 0:
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        # 8.0 时间,内容不能为空
        if cmdType.value == 8.0:
            if cmdValue.ctype == 0:
                print('第',i+1,"行,第2列数据有毛病")
                checkCmd = False
        # 9.0 系统命令集模式,内容不能为空
        if cmdType.value == 9.0:
            if cmdValue.ctype == 0:
                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
            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')
            print("输入:",inputValue) 
            time.sleep(0.5)                                       
        #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
            pyautogui.scroll(int(scroll))
            print("滚轮滑动",int(scroll),"距离")     
       #7代表_热键组合
        elif cmdType.value == 7.0:
            #取重试次数,并循环。
            reTry = 1
            if sheet1.row(i)[2].ctype == 2 and sheet1.row(i)[2].value != 0:
                reTry = sheet1.row(i)[2].value
            inputValue = sheet1.row(i)[1].value
            hotkeyGroup(reTry,inputValue)
            time.sleep(0.5)
       #8代表_粘贴当前时间
        elif cmdType.value == 8.0:      
            #设置本机当前时间。
            localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
            pyperclip.copy(localtime)
            pyautogui.hotkey('ctrl','v')
            print("粘贴了本机时间:",localtime)
            time.sleep(0.5)
       #9代表_系统命令集模式
        elif cmdType.value == 9.0:      
            wincmd = sheet1.row(i)[1].value
            os.system(wincmd)
            print("运行系统命令:",wincmd)
            time.sleep(0.5) 
        i += 1

第六部分:主程序

#主程序
while True:
    if __name__ == '__main__':
        file = 'cmd.xls'
        #打开文件
        wb = xlrd.open_workbook(filename=file)
        #通过索引获取表格sheet页
        sheet1 = wb.sheet_by_index(0)
        print('欢迎使用不高兴就喝水牌RPA~')
        print('大羽改良版_v211207')
        print('')
        #避免多次循环导致的ctrl+v导入到,按ESC进行取消。
        pyautogui.hotkey('esc')
        #数据检查
        checkCmd = dataCheck(sheet1)

        #输入选项实现功能
        if checkCmd:
            key=input('选择功能: 1.做一次 2.循环几次 3.循环到死 0.退出程序\n特殊功能:c.清理屏幕显示\n———————————————————————————————————————\n')
            if key=='1':
                #循环拿出每一行指令 
                print("正在执行第1次命令")  
                print("")
                mainWork(sheet1)
                print("")
                print("已经完成第1次命令")  
                print("——————————————————分割线——————————————————")  
                print("")

            elif key=='2':
                print("")
                count=0
                times=input('输入需要循环的次数,务必输入正整数。\n')
                times=int(times)
                if count < times:
                    while count < times:
                            count+=1 
                            print("正在执行第",count,"次","命令")
                            print("")
                            mainWork(sheet1)
                            time.sleep(0.1)
                            print("等待0.1秒") 
                            print("") 
                            print("已经完成第",count,"次","命令") 
                            print("——————————————————分割线——————————————————")  
                            print("") 
                else:
                    print('输入有误或者已经退出!')
                    os.system('pause')
                    print("") 
                    print("——————————————————————————————————————————")  

            elif key=='3':
                count=0
                while True:
                    count+=1
                    print("正在执行第",count,"次","命令")
                    print("")
                    mainWork(sheet1)
                    time.sleep(0.1)
                    print("等待0.1秒")  
                    print("")
                    print("已经完成第",count,"次","命令")  
                    print("——————————————————分割线——————————————————")  
                    print("")  

            elif key=='0':
                print("正清理缓存文件...")
                os.system('@echo off & for /d %i in (%temp%\^_MEI*) do (rd /s /q "%i")>nul')
                exit("正在退出程序...")
                
            elif key=='c':
                os.system('cls')
                
            else:
                print('输入有误或者已经退出!')
                os.system('pause')
                print("") 
                print("——————————————————————————————————————————")  

实操

实操只需三步,环境库安装→excel按需修改→执行py

原版

第一步:环境库安装

1.安装python3.4以上版本,并配置环境变量(目前有装3.9遇到坑的,我个人用的3.7.6)
2.安装依赖包
方法:在cmd中(win+R 输入cmd 回车)输入
pip install pyperclip 回车
pip install xlrd 回车
pip install pyautogui==0.9.50 回车
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple 回车
pip install pillow 回车

第二步:excel按需修改

3.把每一步要操作的图标、区域截图保存至本文件夹 png格式(注意如果同屏有多个相同图标,回默认找到最左上的一个,因此怎么截图,截多大的区域,是个学问,如输入框只截中间空白部分肯定是不行的,宗旨就是“唯一”)


4.在cmd.xls 的sheet1 中,配置每一步的指令,如指令类型1234 对应的内容填截图文件名(别用中文),指令5对应的内容是等待时长(单位秒) 指令6对应的内容是滚轮滚动的距离,正数表示向上滚,负数表示向下滚,数字大一点,先用200和-200试试
5.保存文件

第三步:执行py

6.双击waterRPA.py打开程序,按1表示excel中的指令执行一次,按2表示无限重复执行直到程序关闭
7.如果报错不能运行用vscode运行看看报错内容(百度vscode安装与运行python程序,将报错内容xxxError后面的贴到百度上面去搜搜看)
8.开始程序后请将程序框最小化,不然程序框挡住的区域是无法识别和操作的
9.如果程序开始后因为你选择了无限重复而鼠标被占用停不下来,alt+F4吧~

可能遇到的问题

一、环境库xlrd

使用pd.read_excel报错
print “EXTERNSHEET(b7-):”
SyntaxError: invalid syntax

pip install –upgrade xlrd


二、双击,右键功能无法实现,或者变成左键单击
调试不行,先退360,退出安全软件后,就可以正常实现功能了。

改版

第一步:环境库安装

安装环境库,同原版操作一致

第二步:excel按需修改

其他按键同原版,新增说明
cmd.xls里增加三个指令:
7热键组合,8本机时间粘贴,9系统命令集(理论上windows和Linxu都可以使用)

热键组合:
解决了原版中无法使用快捷键和键盘录入的问题,命令中的4输入指令,实际为复制粘贴,会占用粘贴板资源。如果你先复制了一个文件,然后在用4指令打开路径,粘贴板中原来复制的文件就会被刚刚的路径所覆盖。

第一列填写7,第二列将需要的组合的热键以英文半角逗号(”,”)分隔填写即可。
例如:win,r ctrl,shift,esc 1,2,3,4,del
当然单个的按键也是可以,热键的名称请查询第一页最后pyautogui库的用法。
但要注意三点:
1)最多10个按键组合,超过则不执行,且后续命令也无法执行。
2)单个数字不识别,且后续命令也无法执行。可能是编程方法使用了hotkey而不是press。
3)英文中的”,”无法被识别,原因是这个符号被用来分隔其他按键组合了。

系统命令集:
调用本系统的命令集,扩展了应用可能性,用批处理写的东西也可以调用了。
理论上windows和Linxu都可以使用,windows是CMD,Linxu应该是command mode

第一列填写9,第二列填写系统指令,第三列重复次数无效。
例如:
start c: (在新窗口中打开C盘)
start cmd (在新窗口中打开CMD程序)

第三步:执行py

来源:方方方钦qiner

物联沃分享整理
物联沃-IOTWORD物联网 » 编写自动化软件+python

发表评论