adb下载安装及使用
通过python调用adb命令实现用元素名称、id、class定位元素
因为懒得搭安卓的sdk环境,所以参考以上两位大佬的文章,用python配合adb实现了一个简单的玩具,要实现别的功能也挺简单的,主要还是要研究xml的元素位置定位,感谢感谢。
目前功能:
- 熄屏和亮屏(亮屏碍于锁屏功能没管)
- 跳转到桌面(主屏)点击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()