python原始封装,不需要三方库实现andorid自动化操作

这个应该不需要pip安装其他库立马就能用,可以用来做一些小的自动化操作
可以看到find_substring和get_coordinate不区分resource-id content text只要ui里面有这个字符串就能定位坐标
但是如果不区分resource-id text content会出现,一个页面可能存在多个这样的字符串
自己封装就可以不用受制于其他工具,改动可以比较大,并且想要其他想法也可以调配

# -*- coding: UTF-8 -*-
import multiprocessing
import subprocess
import os
import re
import time

# 将设备序列号存储在列表中
def get_devices():
    devices = []
    # 运行 adb 命令获取设备列表
    adb_output = subprocess.check_output(['adb', 'devices']).decode('utf-8')
    for line in adb_output.splitlines():
        parts = line.split()
        if len(parts) == 2 and parts[1] == 'device':
            devices.append(parts[0])
    return devices

def find_substring(string,start,end):
    start_index = string.find(start)
    end_index = string.find(end, start_index)
    return string[start_index:end_index]

def update_uitree(serial):
    ui_tree_path = subprocess.check_output(['adb', '-s',serial,'shell', 'uiautomator', 'dump'])
    if(ui_tree_path == b''):
    	time.sleep(3)
    	ui_tree_path = subprocess.check_output(['adb', '-s', serial, 'shell', 'uiautomator', 'dump'])
    ui_tree = subprocess.check_output(['adb', '-s',serial,'shell', 'cat', ui_tree_path.split()[-1]])
    ui_tree = ui_tree.decode("utf-8")
    return ui_tree

def get_tap_command(coordinate,serial):
    x = (coordinate[0] + coordinate[2]) / 2
    y = (coordinate[1] + coordinate[3]) / 2
    tap_command = "adb -s "+serial +" shell input tap " + str(x) + " " + str(y)
    return tap_command
    
def element_is_enabled(serial,text):
    ui_tree = update_uitree(serial)
    sub = find_substring(ui_tree, text, "/>")
    sub = find_substring(sub, "enabled=\"", "\" ")
    aim = sub[9:]
    print(aim)
    if(aim == "true"):
        return True
    if(aim == "false"):
        return False

def is_screen_locked(serial):
    output = subprocess.check_output(['adb','-s',serial,'shell','dumpsys','window','policy']).decode("utf-8")
    # 解析输出来检测屏幕是否解锁
    match = re.search("showing=(false|true)", output)
    print(match)
    if match:
        print(match.group(1))
        showing = match.group(1)
        # 如果showing=true,屏幕未解锁
        return showing == "true"
    return False

def is_screen_off(serial):
    output = subprocess.check_output(['adb', '-s', serial, 'shell', 'dumpsys', 'window', 'policy']).decode("utf-8")
    # 解析输出来检测屏幕是否解锁
    match = re.search("screenState=(SCREEN_STATE_ON|SCREEN_STATE_OFF)", output)
    print(match)
    if match:
        screenState = match.group(1)
        # 如果screenState=SCREEN_STATE_OFF,屏幕已点亮
        print(screenState)
        return screenState == "SCREEN_STATE_OFF"
    return False

def phone_click(serial,text,by="all"):
    ui_tree = update_uitree(serial)
    if(by == "text"):
        coordinate = get_coordinate_by_text(ui_tree, text)
    else:
        coordinate = get_coordinate(ui_tree, text)
    command = get_tap_command(coordinate, serial)
    #print(command)
    subprocess.run(command, stdout=subprocess.DEVNULL)
    
def get_coordinate_by_text(ui_tree,text):
	return get_coordinate(ui_tree,"text=\""+text)
	
def get_coordinate(ui_tree,text):
    sub = find_substring(ui_tree,text,"/>")
    sub = find_substring(sub,"bounds=\"","]\"")
    x1 = find_substring(sub,"[",",")
    x1 = x1[1:]
    y1 = find_substring(sub,",","]")
    y1 = y1[1:]
    x2 = find_substring(sub,"][",",")
    x2 = x2[2:]
    y2 = sub.split(",")[-1]
    x1 = int(x1)
    x2 = int(x2)
    y1 = int(y1)
    y2 = int(y2)
    coordinate = [x1,y1,x2,y2]
    print(text+":",coordinate)
    return coordinate

def test_case(serial):
    #判断是否亮屏,未亮屏就点亮屏幕
    if is_screen_off(serial):
        #subprocess.run(['adb','-s',serial,'shell','input','keyevent','KEYCODE_POWER'])
        subprocess.run("adb -s {} shell input keyevent KEYCODE_POWER".format(serial).split(" "))

    #判断是否解锁,滑动解锁2/3滑倒1/3
    if is_screen_locked(serial):
        size = subprocess.check_output(['adb', '-s', serial,'shell', 'wm', 'size'])
        match = re.search("size:.*", size.decode('utf-8') )
        high = match.group(0).strip().split('x',)[1]
        width = match.group(0).strip().split('x', )[0].split(' ')[1]
        #subprocess.run(['adb', '-s', serial, 'shell', 'input', 'swipe', serial,int(width)/2,int(high)*2/3,int(width)/2,int(high)/3])
        subprocess.run("adb -s {} shell input swipe {} {} {} {}".format(serial,int(width)/2,int(high)*2/3,int(width)/2,int(high)/3).split(" "))
	phone_click(serial,"xxx")


def main():
    devices = get_devices()
    processes = []
    for serial in devices:
        process = multiprocessing.Process(target=test_case, args=(serial,))
        process.start()
        processes.append(process)

        # 等待所有进程完成
    for process in processes:
        process.join()

if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值