Python通过图片识别实现连续点击

一.实现思路

  1. 对整个屏幕进行截图
  2. 将目标点击图与屏幕截图进行对比,找到目标点击图在屏幕截图中的坐标x,y
  3. 实现点击

二.具体实现

需要导入的包

from ctypes import windll
import win32api
import win32con
import time
import aircv as ac
from PIL import ImageGrab

1.对整个屏幕截图

#截取屏幕
#设置休眠时间,方便切换页面
print("请在3秒内切换到需要点击的页面!")
time.sleep(3)
filename = 'screen.png'
im = ImageGrab.grab()
im.save(filename)

2.通过对比获取坐标

#获取x,y
imgsrc = 'screen.png'
#screen.png为屏幕截图文件
imsrc = ac.imread(imgsrc)
imgobj = 'b.png'
#b.png需要识别点击的图片,需要自己上传
imobj = ac.imread(imgobj)
match_result = ac.find_template(imsrc, imobj)
print(match_result)
result = str(match_result)
#注意这里只能为int类型,否则windll.user32.SetCursorPos(x, y)会报错
x = int(result[12:14])
#工具定位为与程序定位会有偏差,横坐标不变,纵坐标减去25左右(根据实际情况调试)
y = int(result[18:21])-25
print(x,y)

3.实现连续点击

for i in range(10):
    # 鼠标移动至指定位置
    windll.user32.SetCursorPos(x, y)
    #鼠标点击操作
    # MOUSEEVENTF_LEFTDOWN为鼠标左键按住,
    # MOUSEEVENTF_LEFTUP为鼠标左键松开,
    # MOUSEEVENTF_RIGHTDOWN为鼠标右键按住,
    # MOUSEEVENTF_RIGHTUP为鼠标右键松开,
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y)
    time.sleep(0.05)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y)
    print("点击")
    #设置休眠方便切换页面,结束程序
    time.sleep(2)
print("点击完成!")

三.完整代码

#实现连续点击屏幕
from ctypes import windll
import win32api
import win32con
import time
import aircv as ac
from PIL import ImageGrab

#截取屏幕
#设置休眠时间,方便切换页面
print("请在3秒内切换到需要点击的页面!")
time.sleep(3)
filename = 'screen.png'
im = ImageGrab.grab()
im.save(filename)

#获取x,y
imgsrc = 'screen.png'
imsrc = ac.imread(imgsrc)
imgobj = 'b.png'
imobj = ac.imread(imgobj)
match_result = ac.find_template(imsrc, imobj)
print(match_result)
result = str(match_result)
#注意这里只能为int类型,否则windll.user32.SetCursorPos(x, y)会报错
x = int(result[12:14])
#工具定位为与程序定位会有偏差,横坐标不变,纵坐标减去25左右(根据实际情况调试)
y = int(result[18:21])-25
print(x,y)

#循环点击
for i in range(10):
    # 鼠标移动至指定位置
    windll.user32.SetCursorPos(x, y)
    #鼠标点击操作
    # MOUSEEVENTF_LEFTDOWN为鼠标左键按住,
    # MOUSEEVENTF_LEFTUP为鼠标左键松开,
    # MOUSEEVENTF_RIGHTDOWN为鼠标右键按住,
    # MOUSEEVENTF_RIGHTUP为鼠标右键松开,
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y)
    time.sleep(0.05)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y)
    print("点击"+str(i))
    #设置休眠方便切换页面,结束程序
    # time.sleep(2)
print("点击完成!")

四.使用步骤

  1. 程序调试好后,将b.png和程序放在同一个目录下。

  2. 运行程序,在3秒内切换到需要点击的页面,运行完成即可。

  • 3
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值