Python+Appium UI自动化代码获取Android多设备信息以及包名
使用appium运行UI自动化代码时,若在脚本中固定写死设备信息,那么每次更换测试设备,就需要在脚本中修改很多东西,比较麻烦,
以下代码可以通过脚本自动获取设备信息:devicesid、deviceName、platformVersion(包含获取单个或多个设备信息)以及包名,具体代码图如下:
import os, re import subprocess # 项目根路径 BaseDIr = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) def get_app_devicesId(): # 获取一个设备的devicesid readDeviceId = list(os.popen('adb devices').readlines()) deviceId = re.findall(r'^\w*\b', readDeviceId[1])[0] return deviceId def get_app_devices(): # 获取多个设备devicesId lists = os.popen('adb devices').read() devices = lists.strip().split('\n') devices_list = [] for i in range(1, len(devices)): device = (devices[i].split('\t')[0]) devices_list.append(device) return devices_list def get_devices_version(): # 获取单个系统版本号 cmd1 = 'adb shell getprop ro.build.version.release' deviceAndroidVersion = list(os.popen(cmd1).readlines()) deviceVersion = re.findall(r'^\w*\b', deviceAndroidVersion[0])[0] return deviceVersion def get_devices_info(devices_uuid): # 获取多设备信息 devices_info = [] cmd1 = 'adb -s {} shell getprop ro.product.model' cmd2 = 'adb -s {} shell getprop ro.build.version.release' if devices_uuid: for de in devices_uuid: device_model = os.popen(cmd1.format(de)).read() deviceos_version = os.popen(cmd2.format(de)).read() devices_info.append((de, device_model.strip('\n'), deviceos_version.strip('\n'))) return devices_info # 获取测试的包的package def get_appPackage(apkPath): appLocation = BaseDIr + apkPath if os.path.exists(appLocation): appPackageAdb = list(os.popen('aapt dump badging ' + appLocation).readlines()) appPackage = re.findall(r'\'com\w*.*?\'', appPackageAdb[0])[0] return appPackage if __name__ == '__main__': # 打印设备信息 devices_uuid = get_app_devices() print(get_devices_info(devices_uuid))
执行结果
[('c1e5c96', 'ONEPLUS A6013', '10')] 'com.wm.dmall'
引包写入desiredCaps中,代码考虑多设备情况:
from common import get_android_infos as andriod_devices if __name__ == '__main__': devices_list = andriod_devices.get_app_devices() # 获取设备devices List devices_info = andriod_devices.get_devices_info(devices_list) # 获取设备信息 appPackage = andriod_devices.get_appPackage("/app_package/D.apk") # 获取appPackage # 根据获取到的设备信息开始写入desiredCaps中,以字典的形式写入 desiredCaps = {} if devices_info: for de in devices_info: desiredCaps = { 'platformName': 'Android', 'platformVersion': '{}'.format(de[2]), 'deviceName': '{}'.format(de[1]), 'udid': '{}'.format(de[0]), 'automationName': 'UiAutomator2', 'appPackage': 'com.wm.dmall', 'appActivity': 'com.wm.dmall.LaunchActivity', 'noReset': 'False' }
每天进步一小步 日积月累跨大步