一.实现思路

  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秒内切换到需要点击的页面,运行完成即可。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐