首页 > 编程语言 >python+uiautomator2判断app是否进入到闪屏广告页面

python+uiautomator2判断app是否进入到闪屏广告页面

时间:2023-06-13 19:24:53浏览次数:47  
标签:screenshot python app activity 广告页面 time path os

  • 前提背景:app内部存在多处广告,需要进行进行自动化:
    1. 查看app是否成功跳转了页面
    2. 页面是否空白
    3. 大致经历的耗时
  • 主要思路如下:点击前进行截图操作,点击后进行判断
  • 判断图片是否空白
    def is_blank(image_path, gray_value=250, threshold=0.9):
        """
        函数会计算一幅图像中超过250(在0到255的灰度值中,255代表白色)的像素的比例,
        如果这个比例超过了阈值(默认为0.05,即5%),那么就判断这幅图像为空白。
        :param image_path:
        :param gray_value:
        :param threshold:
        :return:
        """
    
        # 记录函数开始运行的时间
        # start_time = time.time()
    
        # 打开图像
        img = Image.open(image_path)
        # 将图像转换为灰度模式
        img = img.convert('L')
        # 将图像转换为numpy数组
        img_array = np.asarray(img)
        # 计算图像的总像素
        total_pixels = img_array.shape[0] * img_array.shape[1]
        # 计算图像中白色(或者接近白色)像素的数量
        white_pixels = np.sum(img_array > gray_value)
        # 如果图像中超过一定比例的像素是白色(或接近白色),则判断图像为空白
    
        # 记录函数结束运行的时间
        # end_time = time.time()
        # 计算并打印函数运行的总时间
        # elapsed_time = end_time - start_time
        # print(f"The function took {elapsed_time} seconds to complete.")
        return white_pixels / total_pixels > threshold
  • 图片比较是否相同
    def is_same_image(file1, file2, threshold=10):
        # 打开图片
        img1 = Image.open(file1)
        img2 = Image.open(file2)
    
        # 对比基本信息
        if img1.size != img2.size or img1.mode != img2.mode:
            return False
    
        # 对比像素信息
        for i in range(img1.size[0]):
            for j in range(img1.size[1]):
                p1 = img1.getpixel((i, j))
                p2 = img2.getpixel((i, j))
                diff = sum([abs(p1[k] - p2[k]) for k in range(3)])
                if diff > threshold:
                    return False
        # 两张图片一致
        return True
  • 最后删除图片
    def delete(image_path):
        """
        删除图片
        :param image_path:
        :return:
        """
        if os.path.isfile(image_path):
            os.remove(image_path)
            print('图片删除成功')
  • 获取当前app的activity
    def get_current_activity():
        """
        获取当前页面的activity
        :return:
        """
        cmd = 'adb -s {} shell "dumpsys window | grep mCurrentFocus"'.format(
            get_android_devices())
        activity_info = invoke(cmd).splitlines()
        log.info(activity_info)
        activity = str(activity_info[0]).split("/")[-1][:-1]
        log.info(activity)
        return activity
    

     

  • 完整代码
    import os
    from PIL import Image
    import numpy as np

    activity1 = get_current_activity() save_path = os.path.join(os.getcwd(), 'screenshots') # 保存截图的本地路径 if not os.path.exists(save_path): os.makedirs(save_path) screenshot_name = "闪屏点击前图片.png" screenshot_path1 = os.path.join(save_path, screenshot_name) # 图片保存路径 d.screenshot(screenshot_path1) if d(textContains='第三方应用').exists: d(textContains='第三方应用').click() else: assert False, "不存在对应按钮,需要重新载入新方法" start_time = time.time() time.sleep(3) # 截屏 screenshot_name = "闪屏.png" screenshot_path = os.path.join(save_path, screenshot_name) # 图片保存路径 d.screenshot(screenshot_path) for i in range(0, 3): if is_blank(screenshot_path): delete(screenshot_path) time.sleep(1) screenshot_name = "闪屏.png" screenshot_path = os.path.join(save_path, screenshot_name) # 图片保存路径 d.screenshot(screenshot_path) end_time = time.time() elapsed_time = end_time - start_time if i == 2: assert False, "经过{}秒,当前页面仍然空白".format(elapsed_time) else: delete(screenshot_path) end_time = time.time() elapsed_time = end_time - start_time print("经过{}秒,进入页面".format(elapsed_time)) break # 判断跳转到别的app screenshot_name = "闪屏点击后图片.png" screenshot_path2 = os.path.join(save_path, screenshot_name) # 图片保存路径 d.screenshot(screenshot_path2) if is_same_image(screenshot_path1, screenshot_path2): assert False, "没有跳转任何页面" else: if api.get_current_app() != 'xxx': print("跳转到别的app【{}】".format(api.get_current_app())) else: # 判断跳转到别的非首页的activity if get_current_activity() != activity1: print("跳转到当前app页面:【{}】".format(get_current_activity())) else: print("在app当前页面弹出框") d.app_start('xxx包','xx activity')

     即可进行闪屏点击,判断跳转进入的页面

标签:screenshot,python,app,activity,广告页面,time,path,os
From: https://www.cnblogs.com/zz-1021/p/17478521.html

相关文章

  • 手机APP的开发费用是多少?
    随着移动互联网的快速发展,越来越多的企业和个人开始涉足手机app开发领域。然而,手机APP开发的费用是开发者们最为关心的问题之一。下面思久科技将介绍手机app开发费用的一般预算和主要影响因素,以供参考。一般预算手机APP开发费用的预算因多种因素而异,包括所在地区、开发团队规模、开......
  • Python调用C/C++动态库
    一、编译C++代码并封装成动态库1、创建编译dll文件的项目,在上面的官网介绍的更详细,这里就不多做介绍了。注意在vs之中新建一个项目,项目选择动态链接库(DLL)2、2.在源文件中添加cpp文件并写好函数#include<iostream>#defineMATHLIBRARY_APIextern"C"__declspec(dllexport)......
  • uni-app请求封装
    1.http.js//你的请求地址(线上或线下)exportconstBASE_URL='http://xxx.xxx.xx.xxx:xxxx/'; exportconsthttp=(options)=>{returnnewPromise((resolve,reject)=>{lettoken="",tokenName='';letheader={......
  • uni-app开启消息通知
    场景:uni-app开启移动app,如果用户没开启消息通知提示开启因为uni-app升级到androidx,之前的android.support.v4.app.NotificationManagerCompat已经找不到了,androidx中采用androidx.core.app.NotificationManagerCompat判断是否开启了消息通知 varmain=plus.android.runtime......
  • Python基础之subprocess模块、hashlib模块、日志模块
    subprocess模块tasklist:列举出来文件进程命令"""1.以后我们可以用自己的电脑连接上别人的电脑(socket)2.通过subprocess可以在别人的计算机上执行我们想要执行的命令3.把在别人计算机上执行的结果给返回过来"""importsubprocessimportsubprocessres=subprocess.P......
  • python 之logging 模块
    一、日志的简单使用1、什么是日志记录你的代码在执行过程中的一些变化(记录的是一些有意义的变化)2、日志的5个等级importlogginglogging.debug('debugmessage')#10logging.info('infomessage')#20logging.warning('warningmessage')#30logging.error('errorm......
  • python 3.11.4 安装教程
    python官网 WelcometoPython.org.1.下载python进入官网点击Downloads找到3.11.4版本 点击Download  找到对应的电脑版本进行下载 2.安装python(1)双击下载好的python-3.11.4-amd64.exe(2)勾选AddPython3.7toPATH,再点击CustomizeinstallationInstallno......
  • 苹果自研Apple M1芯片对机器学习意味着什么?
    正文字数:3049 阅读时长:4分钟苹果在iPad和iPhone系列中首次推出了基于苹果A系列处理器的苹果硅片台式机/笔记本电脑处理器。他们推出了这一新的处理器的同时,也推出了三款新的Mac,包括新的M1MacBookAir、M1MacBookPro和M1Macmini。作者/ TommyShrovehttps://netflixtechbl......
  • Python和Anaconda的版本对应关系
    原文链接Python和Anaconda的版本对应关系如下:PackagesincludedinAnaconda2022.10for64-bitLinuxonx86_64CPUswithPython3.10PackagesincludedinAnaconda2022.10for64-bitLinuxonARMv8CPUswithPython3.10PackagesincludedinAnaconda2022.10for6......
  • HP 288G9 主机安装Esxi6.7报错Shutting down firmware services Using simple offset'
    ShuttingdownfirmwareservicesUsingsimpleoffset'UEFIRTSmappingpolicy找了好多方法都不行,尝试1:添加ignoreHeadless=TRUE参数也没救回我电脑,失败尝试2:BIOS中将PCI64bitResourcesHandling里的Above4GDecoding,找不到失败尝试3:PC主板里有一个设置选项叫CSM兼容性......