鸿蒙Next自动化脚本编程软件,适合鸿蒙5.1及以上设备自动化、办公自动化、自动化测试等一系列需要自动处理的事项 使用python语言扩展性可以接入大量第三方库较少开发难度

脚本开发教程(按功能分类)

以下内容按你指定的分类组织,每类都给“用途 + 演示”。脚本默认入口为 def run(device):

下载区

1) 全局模块

  • device:设备操作主体(点击、滑动、启动 App、抓 UI 树等)。
  • ctx:运行上下文(serial/alias/battery/screen_state/foreground_app)。
  • log/print:输出到设备日志窗口。
def run(device):
    log(f"SN={ctx.serial}, alias={ctx.alias}, battery={ctx.battery()}")
    bundle, ability = ctx.foreground_app()
    log(f"foreground={bundle}/{ability}")

2) 节点函数

用于控件查找、点击、输入、拖拽、缩放。

# XPath 选择器
x = device.xpath('//*[@text="登录"]')
if x.exists():
    x.click()

# UiObject 常见操作
node = device(text="搜索")
if node.exists():
    node.click_if_exists()
    node.input_text("关键词")
    # node.clear_text()
    # node.long_click()

3) 图色函数

当前项目主要用截图 + 自定义图像处理(Pillow/OpenCV)方式。

import os, time
from PIL import Image

cap = os.path.join("logs", f"cap_{int(time.time())}.png")
device.screenshot(cap, method="screenCap")
im = Image.open(cap).convert("RGB")
# 这里可做取色、模板匹配、区域判定等

4) OCR识别

项目未内置单一 OCR API,建议“截图 -> OCR库 -> 文本定位”流程。

# 伪代码示例:接入第三方 OCR(如 paddleocr/easyocr)
# 1. device.screenshot("cap.png")
# 2. ocr_texts = ocr.read("cap.png")
# 3. 根据识别结果决定 click/swipe

5) 网络函数

脚本内可直接使用 Python 标准库或第三方网络库。

import urllib.request, json
req = urllib.request.Request("https://httpbin.org/json", method="GET")
with urllib.request.urlopen(req, timeout=8) as resp:
    data = json.loads(resp.read().decode("utf-8"))
log(data.get("slideshow", {}).get("title", ""))

6) 线程函数

适合“后台轮询 + 前台动作”并行场景,注意线程安全和退出条件。

import threading, time

def watcher():
    for _ in range(5):
        ctx.log("后台心跳")
        time.sleep(1)

def run(device):
    t = threading.Thread(target=watcher, daemon=True)
    t.start()
    device.screen_on()

7) 工具函数

建议把通用重试、等待、文本解析封装成函数,降低主流程复杂度。

import time

def retry(fn, rounds=3, delay=0.4):
    last = None
    for _ in range(rounds):
        try:
            return fn()
        except Exception as e:
            last = e
            time.sleep(delay)
    raise last

8) 文件函数

用于保存截图、缓存结果、读写任务配置。

import json, os

os.makedirs("tmp", exist_ok=True)
with open("tmp/result.json", "w", encoding="utf-8") as f:
    json.dump({"serial": ctx.serial, "ok": True}, f, ensure_ascii=False, indent=2)

9) 设备函数

高频使用的设备函数清单(脚本里直接 device.xxx())。

click / fast_click / double_click / long_click
swipe / go_back / go_home / press_key
screen_on / screen_off / unlock
start_app / stop_app / force_start_app
dump_hierarchy / screenshot / shell
input_text / open_url
install_app / uninstall_app / has_app / list_apps
get_app_info / get_app_abilities / get_app_main_ability

10) IDE调试插件

项目已支持 IDE 桥接能力(按 SN 拉日志、远程发停止信号),调试建议:

  • 先看设备日志,再看全局日志。
  • 关键流程打阶段日志(页面识别、点击坐标、重试次数)。
  • 用短循环 + 可复现输入做最小化调试。
def run(device):
    log("step1: start")
    device.screen_on()
    log("step2: dump")
    raw = device.dump_hierarchy()
    log(f"tree_len={len(raw) if isinstance(raw, str) else 'obj'}")