python adb 自动化测试

本文介绍了一种利用Python配合ADB工具实现对Android设备进行控制的方法。文中提供了具体代码实例,展示了如何实现屏幕开关、返回主屏及点击打开指定应用程序等功能,并详细解释了通过元素名称、ID或Class来定位界面元素的具体操作。

adb下载安装及使用
通过python调用adb命令实现用元素名称、id、class定位元素
因为懒得搭安卓的sdk环境,所以参考以上两位大佬的文章,用python配合adb实现了一个简单的玩具,要实现别的功能也挺简单的,主要还是要研究xml的元素位置定位,感谢感谢。

目前功能:

  1. 熄屏和亮屏(亮屏碍于锁屏功能没管)
  2. 跳转到桌面(主屏)点击app打开
import os
import re
import time
import tempfile
import xml.etree.cElementTree as ET

ROOT_DIR = os.path.dirname(__file__)
ADB_DIR = os.path.join(os.path.dirname(ROOT_DIR), "adb")
ADB_PATH = os.path.join(ADB_DIR, "adb.exe")
os.environ["DEBUG"] = "True"

TARGET_DEIVCE_ID = "设备在adb devices命令中显示的id"
class Mobile:
    def __init__(self, device_id, adb_path=ADB_PATH):
        self.device_id = device_id
        self.adb_path = adb_path
        self.temp_dir = tempfile.gettempdir()
        self.pattern = re.compile(r"\d+")
        self.__tmp_ui_name_in_mobile = "uidump.xml"
        self.__tmp_ui_path_in_mobile = f"/data/local/tmp/{self.__tmp_ui_name_in_mobile}"
        self.__tmp_ui_path_in_local = os.path.join(self.temp_dir, self.__tmp_ui_name_in_mobile)
    
    def __execute_cmd(self, cmd):
        if os.environ.get("DEBUG", "False") == "True":
            print(cmd)
        return os.popen(cmd)
    
    def __uidump(self):
        """
        获取当前Activity控件树
        """
        cmd = f"{self.adb_path} shell uiautomator dump {self.__tmp_ui_path_in_mobile}"
        self.__execute_cmd(cmd)
        time.sleep(0.5) # 太快无法正常pull得到文件
        cmd = f"{self.adb_path} pull {self.__tmp_ui_path_in_mobile} {self.temp_dir}"
        self.__execute_cmd(cmd)
        time.sleep(0.5) # 太快无法正常执行后续调用,文件未保存好
    
    def dump_ui(self):
        self.__uidump()
        print(f"{self.__tmp_ui_name_in_mobile} save at {self.__tmp_ui_path_in_local}")
        with open(self.__tmp_ui_path_in_local, "r", encoding="utf-8") as f:
            print(f.read())
    
    def __build_keyevent_cmd(self, keyevent):
        return f"{self.adb_path} shell input keyevent {keyevent}"
        
    def turn_on_screen(self):
        """
        发送按键消息,亮屏
        """
        self.__execute_cmd(self.__build_keyevent_cmd(224))

    def turn_off_screen(self):
        """
        发送按键消息,熄屏
        """
        self.__execute_cmd(self.__build_keyevent_cmd(223))
    
    def click_home(self):
        """
        按下home返回桌面
        """
        self.__execute_cmd(self.__build_keyevent_cmd(3))
    
    def __element(self, attrib, name):
        """
        同属性单个元素,返回单个坐标元组
        """
        self.__uidump()
        tree = ET.ElementTree(file=self.__tmp_ui_path_in_local)
        treeIter = tree.iter(tag="node")
        for elem in treeIter:
            if elem.attrib[attrib] == name:
                bounds = elem.attrib["bounds"]
                coord = self.pattern.findall(bounds)
                Xpoint = (int(coord[2]) - int(coord[0])) / 2.0 + int(coord[0])
                Ypoint = (int(coord[3]) - int(coord[1])) / 2.0 + int(coord[1])
 
                return Xpoint, Ypoint
        print(f"fail find out element of {attrib}:{name}")
        return None, None
 
 
    def __elements(self, attrib, name):
        """
        同属性多个元素,返回坐标元组列表
        """
        list = []
        self.__uidump()
        tree = ET.ElementTree(file=self.__tmp_ui_path_in_local)
        treeIter = tree.iter(tag="node")
        for elem in treeIter:
            if elem.attrib[attrib] == name:
                bounds = elem.attrib["bounds"]
                coord = self.pattern.findall(bounds)
                Xpoint = (int(coord[2]) - int(coord[0])) / 2.0 + int(coord[0])
                Ypoint = (int(coord[3]) - int(coord[1])) / 2.0 + int(coord[1])
                list.append((Xpoint, Ypoint))
        return list
    
    def touch(self, dx, dy):
        """
        触摸事件
        usage: touch(500, 500)
        """
        os.popen(f"{self.adb_path} shell input tap {dx} {dy}")
        time.sleep(0.5)
    
    def findElementByName(self, name):
        """
        通过元素名称定位
        usage: findElementByName(u"设置")
        """
        return self.__element("text", name)
    
    def click_app(self, app_name):
        """
        返回桌面并点击应用
        """
        self.click_home()
        dx, dy = self.findElementByName(app_name)
        if dx and dy:
            self.touch(dx, dy)
            return True
        print(f"fail find out app {app_name}")
        return False

def main():
    m = Mobile(TARGET_DEIVCE_ID)
    # m.turn_on_screen()
    m.click_app("QQ")
    time.sleep(2)
    m.turn_off_screen()


if __name__ == "__main__":
    main()

Python结合ADB实现自动化操作有多种应用场景,以下是不同场景下的方法和示: ### 一键执行多步骤测试流程 Python的`subprocess`模块可将ADB命令封装为Python函数,实现一键执行多步骤测试流程、实时解析命令输出并生成报告,还具备跨平台兼容(Windows/macOS/Linux)的特性 [^1]。 ```python import subprocess def adb_command(command): try: result = subprocess.run(command, shell=True, capture_output=True, text=True) return result.stdout except Exception as e: print(f"Error: {e}") return None # 示:执行多步骤测试流程 # 步骤1:打开设置应用 adb_command('adb shell am start -n com.android.settings/.Settings') # 步骤2:模拟返回操作 adb_command('adb shell input keyevent KEYCODE_BACK') ``` ### 监控进程状态 在Android设备上,可使用Python结合ADB命令编写脚本检测进程状态,并在进程被杀死后检查它们是否重新启动,这在自动化测试和系统稳定性验证中尤为重要 [^2]。 ```python import subprocess import time def check_process_status(process_name): command = f'adb shell ps | grep {process_name}' result = subprocess.run(command, shell=True, capture_output=True, text=True) return result.stdout def monitor_process(process_name): while True: status = check_process_status(process_name) if not status: print(f"{process_name} is killed. Checking if it restarts...") time.sleep(5) # 等待5秒后再次检查 new_status = check_process_status(process_name) if new_status: print(f"{process_name} has restarted.") time.sleep(2) # 每2秒检查一次 # 示:监控Bluetooth进程 monitor_process('Bluetooth') ``` ### 自动刷抖音视频 可以利用Python结合ADB实现自动刷抖音视频,从而自动看视频领取奖励 [^3]。 ```python import subprocess import time def swipe_up(): subprocess.run('adb shell input swipe 500 1500 500 500 200', shell=True) # 示:自动刷视频10次 for _ in range(10): swipe_up() time.sleep(3) # 每次刷完视频等待3秒 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值