用python实现区域找图,模拟点击

今年的双十一活动又有新套路啦,为了领点喵币,得不停地逛店铺,还要等15秒,不如用个小程序来解放自己~
用python实现了一个简易的小程序,主要功能就是自动帮忙逛店铺之类的,思路就是模拟人的操作去点点点。
源码可以在链接中进行下载。更多功能也可以自己实现。


这段小脚本的思路如下:

  1. 从当前手机截屏中找色块(去浏览,去店铺),定位在屏幕中的具体坐标。
  2. 模拟手机点击的操作,点点点,刷刷刷。

准备工作

  1. 假设已经安装好python环境,并且有功能正常的安卓机一台,配有windows环境的电脑一台;
  2. 连接手机需要用到工具安卓调试桥adb,可从adb下载链接中进行下载;
    • 如果是32位系统需要将文件夹下所有文件放置在C:\Windows\System32文件下。
    • 如果是64位系统需要放置在C:\Windows\SysWOW64目录下,如果没有配置相关环境变量可以将adb.exe文件放置在System32文件下。
    • 也可以放在项目的当前路径下。
  3. 使用usb线连接手机和电脑,打开手机的开发人员选项USB调试模式。并且可以在控制台中使用命令adb devices命令来查看命令是否已经能够识别出设备了;
  4. 还要用到python中图像处理识别的相关库,主要有pillowopen-cv。可使用pip命令安装相应的包;
  5. 预先截取好想点击区域的色块,存放在目录之下。

截屏的源代码
# -*- coding: utf-8 -*-
"""
手机屏幕截图的代码: screenshot.py
"""
import subprocess
import os
import sys
from PIL import Image# SCREENSHOT_WAY 是截图方法,经过 check_screenshot 后,会自动递减,不需手动修改
SCREENSHOT_WAY = 2def pull_screenshot():"""获取屏幕截图,目前有 0 1 2 3 四种方法,未来添加新的平台监测方法时,可根据效率及适用性由高到低排序"""global SCREENSHOT_WAYif 1 <= SCREENSHOT_WAY <= 3:process = subprocess.Popen('adb shell screencap -p',shell=True, stdout=subprocess.PIPE)binary_screenshot = process.stdout.read()if SCREENSHOT_WAY == 2:binary_screenshot = binary_screenshot.replace(b'\r\n', b'\n')elif SCREENSHOT_WAY == 1:binary_screenshot = binary_screenshot.replace(b'\r\r\n', b'\n')f = open('tmall.png', 'wb')f.write(binary_screenshot)f.close()elif SCREENSHOT_WAY == 0:os.system('adb shell screencap -p /sdcard/tmall.png')os.system('adb pull /sdcard/tmall.png .')def check_screenshot():"""检查获取截图的方式"""global SCREENSHOT_WAYif os.path.isfile('tmall.png'):try:os.remove('tmall.png')except Exception:passif SCREENSHOT_WAY < 0:print('暂不支持当前设备')sys.exit()pull_screenshot()try:Image.open('./tmall.png').load()print('采用方式 {} 获取截图'.format(SCREENSHOT_WAY))except Exception:SCREENSHOT_WAY -= 1check_screenshot()
在手机界面找图并模拟点击源码
# -*- coding: utf-8 -*-
import os
import time
import screenshot
import cv2
from threading import Thread"""
模拟点击的源代码: tmall.py
"""adbShell = "adb shell {cmdStr}"def execute(cmd):str = adbShell.format(cmdStr=cmd)print(str)os.system(str)def find_button(target, template):"""寻找target图片在template中的位置,返回应该点击的坐标。"""theight, twidth = target.shape[:2]# 执行模板匹配,采用的匹配方式cv2.TM_SQDIFF_NORMEDresult = cv2.matchTemplate(target, template, cv2.TM_SQDIFF_NORMED)min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)# 如果匹配度小于99%,就认为没有找到。if min_val > 0.01:return Nonestrmin_val = str(min_val)print(strmin_val)# 绘制矩形边框,将匹配区域标注出来# cv2.rectangle(template, min_loc, (min_loc[0] + twidth, min_loc[1] + theight), (0, 0, 225), 2)# cv2.imshow("MatchResult----MatchingValue="+strmin_val, template)# cv2.imwrite('1.png', template, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])# cv2.waitKey()# cv2.destroyAllWindows()x = min_loc[0] + twidth//3y = min_loc[1] + theight//3return (x, y)def fun1():os.system("adb nodaemon server") # 如果adb服务器不能正常启动,可以开另一个线程调用该函数。def fun2():swip = Truewhile True:screenshot.pull_screenshot() # 截图tar = 'gol'		# 判断是否有去浏览按钮# temp = cv2.imread('./test.jpg')temp = cv2.imread('./tmall.png')target = cv2.imread('./'+tar+'.png')pos = find_button(target, temp)if pos:execute("input tap {:d} {:d}".format(pos[0], pos[1]))time.sleep(2)execute("input swipe 100 1200 100 208")execute("input swipe 100 1200 100 208")time.sleep(18)execute("input keyevent 4")		# 返回按键time.sleep(2)elif swip:	# 向下滑动看看有没有遗漏execute("input swipe 580 1600 580 1100")swip = Falseelse:breakexecute("input swipe 580 1100 580 1600")swip = Truewhile True:screenshot.pull_screenshot()tar = 'god'		# 判断是否有去店铺按钮temp = cv2.imread('./tmall.png')target = cv2.imread('./'+tar+'.png')pos = find_button(target, temp)# print(pos)if pos:execute("input tap {:d} {:d}".format(pos[0], pos[1]))time.sleep(2)execute("input swipe 100 1200 100 208")execute("input swipe 100 1200 100 208")time.sleep(18)execute("input keyevent 4")time.sleep(2)elif swip:execute("input swipe 580 1600 580 1100")swip = Falseelse:breakif __name__ == '__main__':thread_2 = Thread(target=fun2)thread_2.start()thread_2.join()print('finished!')


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部