使用python实现 大批量的自动搜索安装apk

序言

最近业务上需要大量安装apk。想通过python边写自动化脚本来实现。经过研究,达到了预期。现在把这个过程中遇到的一些问题记录下来,帮助大家在相同场景下更快更好的实现。

效果

可以自动读取Excel中需要安装的apk的名单。最后把搜索结果和安装结果回写到Excel中。 安装效果

实现

方案选择

这次主要使用了airTest来实现。为什么用airTest。因为airTest可以基于图像识别,也可以基于API。而且可以手动编写脚本,也可以基于IDE。还是跨平台的。文档比较全面。还是网易开发的,对中文文档的支持也很好。

脚本

python 复制代码
# -*- encoding=utf8 -*-
__author__ = "W9075443"

from airtest.core.api import *
from airtest.core.android.android import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import pandas as pd

auto_setup(__file__)

poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
dev = Android()

def get_need_install_apk_names():
    # 读取 Excel 文件
    df = pd.read_excel("E:\\System Desktop\\需要安装的应用列表.xlsx",engine="openpyxl")
    app_names = df.iloc[:, 0]
    return (df,app_names.values)
   

def search_and_install_app(app_name):
    if(exists(Template(r"tpl1750439272563.png", record_pos=(0.243, -0.944), resolution=(1260, 2844)))):
        touch(Template(r"tpl1750439302415.png", record_pos=(0.244, -0.944), resolution=(1260, 2844)))

    detail_search_bar= poco("com.huawei.appmarket:id/search_src_text")
    detail_search_bar.click()
    text(app_name)   
    search_result=get_search_result(app_name)
    if(search_result[0]):
        print("找到相关应用")
        if(search_result[1]):
            print("应用已安装")
            return (True,True)
        else:
         #启动安装
            print("开始安装")
            search_result[2].click()
            wait_for_install(search_result[3])
            return (True,True)    
    else:
        print(f"没有找到要搜索的应用:{app_name}")
        return (False,False)
    


def wait_for_install(root_element):
    while True:
        install_button=tv_status=install_button=root_element.offspring("com.huawei.appmarket:id/hwprogressbutton_percentage_text_view")  
        text=install_button.get_text()
        if(text=='继续'):
            print("安装失败")
            return (False,'安装过程出问题')
        elif(text=='打开'):
            print("安装成功")
            return (True,'安装成功')
        else:
            print("正在安装:"+text)
            sleep(1)


#方法用来返回搜索结果
def get_search_result(search_app_name):
    sleep(2)
    tv_names=poco("com.huawei.appmarket:id/ItemTitle")
    tv_status=poco("com.huawei.appmarket:id/hwprogressbutton_percentage_text_view")
    print("打印child")
    print(len(tv_names))
    # 遍历每个父元素
    for index,tv_name in enumerate(tv_names):
        print("打印child_element.get_text()")
        print(tv_name.get_text())
        if (search_app_name==tv_name.get_text()):
            # 获取子元素的文本内容
            app_name = tv_name.get_text()
            print(f"显示的应用名称为{app_name}")
            root_element=tv_name.parent().parent()         
            install_button=root_element.offspring("com.huawei.appmarket:id/hwprogressbutton_percentage_text_view")                            
            app_status=install_button.get_text()            
            return (True,app_status=='打开',install_button,root_element)           
    return (False,False,None,None)


            

#com.huawei.appmarket/.MarketActivity
#打开华为应用市场
start_app("com.huawei.appmarket")

home_search_bar=poco("com.huawei.appmarket:id/search_bar")

home_search_bar.click()

excel= get_need_install_apk_names()

for index,app_name in enumerate(excel[1]):
    search_and_install_result=search_and_install_app(app_name)
    #写入结果
    searchReuslt="没有搜索到"
    if(search_and_install_result[0]):
        searchReuslt="搜索成功"
    install_result="安装失败"
    if(search_and_install_result[1]):
        install_result="安装成功"
    excel[0].iloc[index+1, 1] = searchReuslt
    excel[0].iloc[index+1, 2] = install_result
    # 再写回 Excel
    excel[0].to_excel("E:\\System Desktop\\需要安装的应用列表.xlsx", index=False)    

注意的点

airTest的下载

在官网下载就行了,免费,免安装的绿色软件 airTest的官网 可以选择中文

airTest对第三方库的支持

airTest内置了python环境。但是在我的脚本中使用到了pandas这个库,用来操作Excel。只用内置的库的话,就好出现找不到库要报错。所以需要配置airTest使用我们自己的python环境。官方也有文档说明。 文档地址如下 Airtest Project Docs AirtestIDE常见问题 需要注意的点主要是python版本,最高只支持python 3.9

课程推荐

推荐bilibili中的课程。 理论到实战结合-带你掌握AirTest自动化测试

获取id

使用airTest自带的poco辅助窗就可以获取控件的id。 第一步需要在连接号设备以后,锁定画面。 第二步选择Android 第三步点击想要获取id的控件。 第四步可以在log查看窗中获取控件的相关信息,使用name作为poco选择的id 最后需要注意的是我在搜索过程中发现,结果页的UI元素会有变化。比如有广告和没广告。所以有时候遇到找不到元素。可以看看是不是两次分析的UI树结构不一样。经量找一些末端没有变化的id作为查找的依据。

相关推荐
fatiaozhang95272 小时前
创维智能融合终端SK-M424_S905L3芯片_2+8G_安卓9_线刷固件包
android·电视盒子·刷机固件·机顶盒刷机
来来走走3 小时前
Flutter开发 了解Scaffold
android·开发语言·flutter
哆啦A梦的口袋呀5 小时前
Android 底层实现基础
android
闻道且行之5 小时前
Android Studio下载及安装配置
android·ide·android studio
alexhilton5 小时前
初探Compose中的着色器RuntimeShader
android·kotlin·android jetpack
小墙程序员5 小时前
kotlin元编程(二)使用 Kotlin 来生成源代码
android·kotlin·android studio
小墙程序员6 小时前
kotlin元编程(一)一文理解 Kotlin 反射
android·kotlin·android studio
fatiaozhang95277 小时前
创维智能融合终端DT741_移动版_S905L3芯片_安卓9_线刷固件包
android·电视盒子·刷机固件·机顶盒刷机
小林学Android9 小时前
Android四大组件之Activity详解
android
搬砖不得颈椎病9 小时前
Jetpack DataStore vs SharedPreferences:现代Android数据存储方案对比
android