程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(2)

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

发布于2019-10-28 15:44     阅读(4753)     评论(0)     点赞(12)     收藏(4)


利用python实现手机区域找色,模拟点击功能

借助adb工具包实现手机的区域找图,模拟点击功能,具体demo可详见https://blog.csdn.net/wz2671/article/details/102751549。

立即下载

今年的双十一活动又有新套路啦,为了领点喵币,得不停地逛店铺,还要等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 = 2


def pull_screenshot():
    """
    获取屏幕截图,目前有 0 1 2 3 四种方法,未来添加新的平台监测方法时,
    可根据效率及适用性由高到低排序
    """
    global SCREENSHOT_WAY
    if 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_WAY
    if os.path.isfile('tmall.png'):
        try:
            os.remove('tmall.png')
        except Exception:
            pass
    if SCREENSHOT_WAY < 0:
        print('暂不支持当前设备')
        sys.exit()
    pull_screenshot()
    try:
        Image.open('./tmall.png').load()
        print('采用方式 {} 获取截图'.format(SCREENSHOT_WAY))
    except Exception:
        SCREENSHOT_WAY -= 1
        check_screenshot()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

在手机界面找图并模拟点击源码

# -*- 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_NORMED
    result = 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 None
    strmin_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//3
    y = min_loc[1] + theight//3
    return (x, y)


def fun1():
    os.system("adb nodaemon server") # 如果adb服务器不能正常启动,可以开另一个线程调用该函数。


def fun2():
    swip = True

    while 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 = False
        else:
            break

    execute("input swipe 580 1100 580 1600")
    swip = True

    while 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 = False
        else:
            break


if __name__ == '__main__':

    thread_2 = Thread(target=fun2)
    thread_2.start()
    thread_2.join()
    print('finished!')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106


所属网站分类: 技术文章 > 博客

作者:放羊人

链接:https://www.pythonheidong.com/blog/article/147077/c1c4735b2b26218984ef/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

12 0
收藏该文
已收藏

评论内容:(最多支持255个字符)