受到水哥视频(5分钟,教你做个自动化软件拿来办公、刷副本、回微信 | 源码公开,开箱即用_哔哩哔哩_bilibili)的启发,对机器人流程自动化,即RPA(Robotic Process Automation)很感兴趣。在网上一搜发现已经有公司开发出成熟的软件,用来完成自动化操作。在我的印象里,能达到这种效果的就是按键精灵了,几乎算是无门槛,玩游戏做每日任务的神器。
也找了款软件——影刀,上手体验了一下,主要是B站上有教程,省去摸索的时间。影刀可以直接录制操作,很方便,还能插入Python代码。不过都用软件代替了,还去写啥代码,直接在屏幕上图片识别,做逻辑判断,重复操作,巨省事。
视频里展示的原文件和源码在百度网盘:waterRPA-百度网盘 。
我挑出最感兴趣的部分,在本地环境简单实现了一下。
Version 1:
import pyautogui
import time
import logging
# 设置日志模块
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
# 图片路径列表
image_list = ['image1.png', 'image2.png']
def click_image(image_path, max_retries=3, confidence=0.8):
"""尝试定位并点击屏幕上的指定图片"""
# 重试次数计数器
for attempt in range(1, max_retries + 1):
logging.info(f"正在进行第{attempt}次尝试,定位图片'{image_path}'。")
try:
# 定位图片中心坐标
image_location = pyautogui.locateCenterOnScreen(image_path, confidence=confidence)
if image_location is not None:
# 点击图片中心
pyautogui.click(image_location.x, image_location.y)
# 记录成功点击信息
logging.info(f"成功在第{attempt}次点击图片'{image_path}'。")
return
except Exception as e:
logging.warning(f"未能在第{attempt}次尝试中匹配图片'{image_path}',原因:{e}")
logging.info(f"剩余重试次数:{max_retries - attempt}次。")
# 每次失败后等待一秒再重试
time.sleep(1)
# 所有重试次数用尽后记录错误信息
logging.error(f"经过{max_retries}次重试后,仍未找到图片'{image_path}'。")
# 遍历图片列表,对每个图片调用点击函数
for image in image_list:
click_image(image)
要注意的是locateCenterOnScreen()函数,如果使用了confidence参数,需要先安装OpenCV库,提供分辨图像相似度的支持。
pip install opencv-python
Version 2:
做了一些小修改,尝试在屏幕上匹配我提供的蛋糕图片和炸弹图片,匹配到了按下规定的按键
import pyautogui
import time
# 图片路径与键值对应字典简写为 img_key_map
img_key_map = {'C:\Images\Cake.png': 'A', 'C:\Images\Bombs.png': 'D'}
def find_and_press(image_path, retries=3, conf=0.9):
for try_count in range(1, retries + 1):
print(f"尝试 {try_count},查找图片'{image_path}'。")
try:
img_pos = pyautogui.locateCenterOnScreen(image_path, confidence=conf)
if img_pos is not None:
key_to_press = img_key_map[image_path]
pyautogui.press(key_to_press)
print(f"在第{try_count}次尝试中找到图片'{image_path}'并按下了'{key_to_press}'键。")
return
except Exception as e:
print(f"尝试 {try_count} 中未能匹配图片'{image_path}',原因:{e}")
print(f"剩余重试次数:{retries - try_count} 次。")
time.sleep(0.3)
print(f"经过{retries}次重试后,仍未找到图片'{image_path}'。")
if __name__ == '__main__':
for img, key in img_key_map.items():
find_and_press(img)
用pyautogui库模拟鼠标和键盘的操作的时候,用户就不能对键鼠进行操作了,会干扰程序的运行。