{"id":50339670,"url":"https://github.com/ziguiway/hmnextauto","last_synced_at":"2026-06-15T07:01:42.913Z","repository":{"id":355334291,"uuid":"1225369332","full_name":"ziguiway/hmnextauto","owner":"ziguiway","description":"UI Automation Framework for HarmonyOS NEXT - uiautomator2-compatible API, zero learning cost","archived":false,"fork":false,"pushed_at":"2026-05-03T03:44:05.000Z","size":5835,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-03T05:15:38.770Z","etag":null,"topics":["automation-testing","harmony","harmonyos","harmonyos-next","harmonyosnext","hdc","mobile-testing","python","ui-automation","uiautomator2"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/hmnextauto/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ziguiway.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-04-30T07:56:02.000Z","updated_at":"2026-05-03T03:44:06.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ziguiway/hmnextauto","commit_stats":null,"previous_names":["ziguiway/hmnextauto"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/ziguiway/hmnextauto","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziguiway%2Fhmnextauto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziguiway%2Fhmnextauto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziguiway%2Fhmnextauto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziguiway%2Fhmnextauto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ziguiway","download_url":"https://codeload.github.com/ziguiway/hmnextauto/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziguiway%2Fhmnextauto/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34351451,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-15T02:00:07.085Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["automation-testing","harmony","harmonyos","harmonyos-next","harmonyosnext","hdc","mobile-testing","python","ui-automation","uiautomator2"],"created_at":"2026-05-29T16:00:25.046Z","updated_at":"2026-06-15T07:01:42.906Z","avatar_url":"https://github.com/ziguiway.png","language":"Python","funding_links":[],"categories":["UI Testing"],"sub_categories":[],"readme":"# HMNextAuto 鸿蒙自动化框架\n\n[![PyPI version](https://img.shields.io/pypi/v/hmnextauto.svg)](https://pypi.python.org/pypi/hmnextauto)\n[![Python](https://img.shields.io/pypi/pyversions/hmnextauto.svg)](https://pypi.org/project/hmnextauto)\n[![License](https://img.shields.io/github/license/ziguiway/HMNextAuto.svg)](https://github.com/ziguiway/HMNextAuto/blob/main/LICENSE)\n[![Downloads](https://pepy.tech/badge/hmnextauto)](https://pepy.tech/project/hmnextauto)\n\n\u003e **持续维护的鸿蒙 NEXT 无侵入式 UI 自动化框架**，对齐 uiautomator2 API，零学习成本！\n\n***\n\n## 🌍 项目背景\n\n随着华为鸿蒙 NEXT 系统的正式发布，纯血鸿蒙生态正在快速崛起。与传统 HarmonyOS 不同，HarmonyOS NEXT 不再兼容 Android 应用，这意味着基于 Android 的自动化测试框架（如 uiautomator2）将无法在新系统上运行。\n\n在这样的背景下，原 [hmdriver2](https://github.com/codematrixer/hmdriver2) 项目应运而生，它是首款支持 HarmonyOS NEXT 的无侵入式 UI 自动化框架，为开发者提供了轻量高效的自动化测试能力。然而，由于原作者工作变动等原因，该项目已经两年没有更新维护。\n\n为了让这款优秀的框架继续服务于广大鸿蒙开发者，我基于原 `hmdriver2` 的核心架构，完成了大量的 Bug 修复、功能增强和稳定性优化。**HMNextAuto** 由此诞生！\n\n***\n\n## 🌟 核心优势\n\n| 特性          |       HMNextAuto       | Hypium (官方) | 原版 hmdriver2 |\n| ----------- | :--------------------: | :---------: | :----------: |\n| 无侵入式        |            ✅           |  ❌ 需安装测试框架  |       ✅      |\n| 学习成本        |     🟢 零学习成本（对齐 u2）    |    🔴 较高    |  🟡 需熟悉 API  |\n| 维护状态        |         ✅ 持续更新         |    ✅ 官方维护   |  ❌ 停止维护 2 年  |\n| 视觉定位        |        ✅ 多尺度模板匹配       |      ❌      |       ❌      |\n| 找色点击        |       ✅ RGB 容差匹配       |      ❌      |       ❌      |\n| 后台 Watcher  |      ✅ 纯 Python 实现     |      ❌      |       ✅      |\n| XPath 多元素操作 | ✅ count/all/first/last |      ❌      |       ❌      |\n| 通知栏操作       |        ✅ 完整通知栏控制       |      ❌      |       ❌      |\n| 性能监控        |        ✅ 后台性能采集        |      ❌      |       ❌      |\n| 智能等待条件      |      ✅ wait\\_until     |      ❌      |       ❌      |\n| 依赖复杂度       |   🟢 仅 lxml + opencv   |     🔴 重    |     🟢 轻     |\n\n***\n\n## 📋 系统要求\n\n| 项目     | 要求                                 |\n| ------ | ---------------------------------- |\n| Python | 3.8+                               |\n| 操作系统   | Windows / macOS / Linux            |\n| 设备     | HarmonyOS NEXT (API 12+)           |\n| 工具     | HDC (HarmonyOS Command Line Tools) |\n\n***\n\n## 🚀 快速开始\n\n### 1. 安装 HDC 工具\n\n下载 [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/cn/download/) 并配置环境变量：\n\n```bash\n# macOS / Linux\nexport HM_SDK_HOME=\"/path/to/sdk\"\nexport PATH=$PATH:$HM_SDK_HOME/openharmony/toolchains\n\n# Windows (系统环境变量)\nHM_SDK_HOME=C:\\path\\to\\sdk\nPATH=%PATH%;%HM_SDK_HOME%\\openharmony\\toolchains\n```\n\n### 2. 连接设备\n\n开启 USB 调试，确认设备连接：\n\n```bash\nhdc list targets\n# 输出设备序列号即连接成功\n```\n\n### 3. 安装 HMNextAuto\n\n```bash\npip install -U hmnextauto\n```\n\n### 4. 验证安装\n\n```python\nfrom hmnextauto.driver import Driver\n\nd = Driver()\nprint(d.device_info)\n# 输出设备信息即配置成功\n```\n\n***\n\n## ✨ 增强功能详解\n\n\u003e 以下功能均为 HMNextAuto 相比原版 hmdriver2 的**新增增强功能**\n\n### 1. XPath 多元素操作 🆕\n\n支持对匹配到的多个元素进行批量操作：\n\n```python\n# 获取匹配元素数量\ncount = d.xpath('//*[@clickable=\"true\"]').count\n\n# 获取所有匹配元素\nelements = d.xpath('//*[@clickable=\"true\"]').all()\nfor el in elements:\n    print(el.bounds)\n    el.click()\n\n# 快速获取首/末元素\nfirst = d.xpath('//*[@clickable=\"true\"]').first()\nlast = d.xpath('//*[@clickable=\"true\"]').last()\n```\n\n### 2. 通知栏操作 🆕\n\n完整的下拉通知栏和快捷开关控制：\n\n```python\n# 打开通知栏（消息中心）\nd.notification.open()\n\n# 打开快捷设置面板\nd.notification.open_quick_settings()\n\n# 点击快捷开关\nd.notification.click_quick_setting(\"wifi\")        # WiFi\nd.notification.click_quick_setting(\"bluetooth\")   # 蓝牙\nd.notification.click_quick_setting(\"airplane\")    # 飞行模式\nd.notification.click_quick_setting(\"flashlight\")  # 手电筒\n\n# 设置亮度 (0-255)\nd.notification.set_brightness(128)\n\n# 关闭通知栏\nd.notification.close()\n```\n\n### 3. 性能监控与分析 🆕\n\n后台自动采集设备性能数据，支持深度分析和报告生成：\n\n```python\n# 基础用法 - 后台采集\nwith d.performance_watcher.start(\"perf.jsonl\", interval=0.5):\n    d(text=\"按钮\").click()\n    # ... 执行测试 ...\n\n# 高级用法 - 选择性采集（推荐，更快）\nd.performance_watcher.configure(\n    metrics=[\"fps\", \"cpu\", \"memory\", \"hitches\"],\n    package=\"com.example.app\",  # 指定包名加速内存采集\n    interval=0.5\n).start(\"perf.jsonl\")\n\n# 深度分析\nanalyzer = d.performance_watcher.analyze()\n\n# 统计摘要\nstats = analyzer.stats()\nprint(f\"FPS 平均: {stats.fps.avg}, P95: {stats.fps.p95}\")\nprint(f\"内存峰值: {stats.memory_peak_mb:.1f} MB\")\n\n# 异常检测\nanomalies = analyzer.detect_anomalies()\nfor a in anomalies:\n    print(f\"[{a.severity.value}] {a.message}\")\n\n# 性能评分（S/A/B/C/D/F 等级）\nscore = analyzer.score()\nprint(f\"性能等级: {score.grade} ({score.total}/100)\")\n\n# 生成 HTML 报告（带图表）\nanalyzer.generate_report(\"report.html\", include_charts=True)\n```\n\n**性能指标采集速度**：\n\n| 指标 | 命令 | 耗时 | 建议 |\n|------|------|------|------|\n| FPS | `hidumper -s RenderService -a fps` | ~0.3s | ✅ 推荐 |\n| CPU | `hidumper --cpuusage` | ~0.3s | ✅ 推荐 |\n| 内存(指定PID) | `hidumper --mem \u003cPID\u003e` | ~1.5s | ✅ 指定 package |\n| 内存(全系统) | `hidumper --mem` | ~40s | ❌ 不推荐 |\n| 卡顿 | `hidumper -s RenderService -a hitchs` | ~0.2s | ✅ 推荐 |\n| CPU温度 | `hidumper -s ThermalService -a '-t'` | ~0.5s | ✅ 推荐 |\n| 内存使用率 | `cat /proc/meminfo` | ~0.2s | ✅ 推荐 |\n\n\u003e 💡 **性能提示**: 设置 `package` 参数可将内存采集从 40 秒降至 1-2 秒！\n\n### 4. 智能等待条件 🆕\n\n更丰富的控件等待条件：\n\n```python\n# 等待控件可点击\nd(text=\"按钮\").wait_clickable(timeout=10)\n\n# 等待控件启用\nd(text=\"输入框\").wait_enabled(timeout=5)\n\n# 自定义等待条件\nd(text=\"列表\").wait_until(lambda el: el.info[\"scrollable\"], timeout=10)\n```\n\n### 5. 视觉定位能力\n\n```python\n# 图像匹配点击（支持多尺度）\nok = d.click_image(\"target.png\", threshold=0.88)\n\n# 找色点击（RGB 容差匹配）\nd.click_color((255, 0, 0), tolerance=12)\n\n# 限制区域找色\nd.click_color((0, 160, 255), tolerance=10, region=(100, 400, 600, 1200))\n```\n\n### 6. 后台 Watcher 自动处理弹窗\n\n```python\n# 自动处理常见弹窗\nd.watcher(\"ad\").when_xpath('//*[@text=\"跳过\"]').click()\nd.watcher(\"ok\").when(text=\"确定\").click()\nd.watcher.start(interval=0.3)\n\n# 主流程执行\nd.start_app(\"com.example.app\")\n\nd.watcher.stop()\n```\n\n### 7. 模糊匹配选择器\n\n```python\n# 子串匹配\nd(textContains=\"登\").click()\n\n# 正则匹配\nd(textMatches=r\"^\\d+条$\").click()\n\n# 资源 ID 模糊匹配\nd(resourceIdContains=\"entry\", type=\"Button\").click()\n```\n\n***\n\n## 🔄 从 uiautomator2 无缝迁移\n\n如果你熟悉 Android 的 `uiautomator2`，**零学习成本**直接上手：\n\n```python\n# uiautomator2 写法\nfrom uiautomator2 import Device\nd = Device()\nd(text=\"精选\").click()\nd.swipe(0.5, 0.8, 0.5, 0.2)\n\n# HMNextAuto 写法（完全一致！）\nfrom hmnextauto.driver import Driver\nd = Driver()\nd(text=\"精选\").click()\nd.swipe(0.5, 0.8, 0.5, 0.2)\n```\n\n***\n\n## 📚 API 速查\n\n\u003e 💡 **详细 API 文档**: [docs/API.md](docs/API.md) - 完整的 API 文档，包含所有功能说明和示例代码\n\n### App 管理\n\n```python\nd.install_app(\"demo.hap\")              # 安装应用\nd.uninstall_app(\"com.example.app\")     # 卸载应用\nd.start_app(\"com.example.app\")         # 启动应用\nd.stop_app(\"com.example.app\")          # 停止应用\nd.clear_app(\"com.example.app\")         # 清除数据\nd.start_app_by_name(\"微信\")            # 用应用名启动\nd.force_start_app(\"com.example.app\")   # 强制启动（回桌面+停+启）\n```\n\n### 设备操作\n\n```python\nd.press_home()                         # Home 键\nd.press_back()                         # 返回键\nd.screen_on()                          # 亮屏\nd.screen_off()                         # 息屏\nd.unlock()                             # 解锁\nd.open_url(\"https://baidu.com\")        # 打开 URL\nd.screenshot(\"screen.png\")             # 截图\n```\n\n### 控件操作\n\n```python\nd(text=\"确定\").click()                 # 点击\nd(text=\"确定\").click_if_exists()       # 存在才点击\nd(text=\"输入框\").input_text(\"hello\")   # 输入文本\nd(text=\"输入框\").clear_text()          # 清除文本\nd(type=\"Button\").count                 # 控件数量\nd(text=\"按钮\").info                    # 控件信息\nd(text=\"列表\").scroll.to(text=\"目标\")  # 滚动查找\n```\n\n### 手势操作\n\n```python\nd.click(0.5, 0.5)                      # 单击（支持百分比坐标）\nd.double_click(0.5, 0.5)               # 双击\nd.long_click(0.5, 0.5)                 # 长按\nd.swipe(0.5, 0.8, 0.5, 0.4)            # 滑动\nd.swipe_ext(\"up\", scale=0.8)           # 方向滑动\nd.gesture.start(100, 200).move(300, 400).action()  # 自定义手势\n```\n\n### 录屏\n\n```python\n# 推荐方式（自动清理资源）\nwith d.screenrecord.start(\"test.mp4\"):\n    d(text=\"按钮\").click()\n```\n\n***\n\n## 🔍 UI Inspector 工具\n\n配合 **uiautodev** 可视化查看控件树：\n\n```bash\npip install \"uiautodev[harmony]\"\nuiauto.dev\n# 打开浏览器访问 http://localhost:20242\n```\n\n功能特性：\n\n- 实时查看控件树层级\n- 自动生成 XPath\n- 查看控件属性详情\n\n项目地址：\u003chttps://github.com/codeskyblue/uiautodev\u003e\n\n***\n\n## 🎯 应用场景\n\n| 场景        | 说明        |\n| --------- | --------- |\n| App 自动化测试 | 功能测试、回归测试 |\n| 性能测试      | 配合录屏分析    |\n| 自动化运营     | 批量操作脚本    |\n| UI 截图对比   | 视觉回归测试    |\n| 兼容性测试     | 多设备并行     |\n\n***\n\n## ❓ 常见问题\n\n### Q: 找不到设备？\n\n确保已开启 USB 调试，运行 `hdc list targets` 确认连接。\n\n### Q: pip 安装失败？\n\n尝试使用镜像：\n\n```bash\npip install -U hmnextauto -i https://pypi.tuna.tsinghua.edu.cn/simple\n```\n\n### Q: 图像匹配不准确？\n\n调整 `threshold` 参数（默认 0.85），或使用更高分辨率的模板图片。\n\n### Q: 如何连接远程设备？\n\n```bash\nexport HDC_SERVER_HOST=192.168.1.100\nexport HDC_SERVER_PORT=8710\n```\n\n### Q: 控件找不到？\n\n使用 UI Inspector 工具查看控件属性，确认选择器是否正确。\n\n### Q: 如何使用 OCR 文字识别？\n\nOCR 功能需要额外安装依赖：\n\n```bash\npip install hmnextauto[ocr]\n```\n\n使用示例：\n\n```python\n# 识别屏幕所有文字\nresults = d.ocr.read()\n\n# 查找文字位置\npos = d.ocr.find_text(\"登录\")\n\n# 点击文字\nd.ocr.click_text(\"确定\")\n\n# 等待文字出现\nd.ocr.wait_text(\"加载完成\", timeout=30)\n```\n\n***\n\n## 📅 更新日志\n\n| 版本     | 日期         | 主要更新                               |\n| ------ | ---------- | ---------------------------------- |\n| v1.7.0 | 2026-05-06 | 新增 CPU 温度、内存使用率指标，报告模板支持新指标展示 |\n| v1.6.1 | 2026-05-06 | 性能监控优化：并行采集、内存采集提速 20 倍（指定 PID） |\n| v1.6.0 | 2026-05-06 | 新增性能数据分析工具（异常检测、评分、HTML 报告）     |\n| v1.5.0 | 2026-05-06 | 新增 OCR 文字识别功能（可选依赖）             |\n| v1.4.0 | 2026-05-03 | 新增全局隐式等待 `implicitly_wait`，Settings 配置管理 |\n| v1.3.0 | 2026-04-30 | 新增通知栏操作、XPath 多元素操作、性能监控、智能等待条件 |\n| v1.2.0 | 2026-04-29 | 升级 uitest\\_agent v1.2.2，统一调用逻辑     |\n| v1.1.0 | 2026-04-24 | 新增视觉定位功能（多尺度模板匹配、找色点击）             |\n| v1.0.5 | 2026-04-23 | XPath wait/wait\\_gone 方法           |\n| v1.0.0 | 2026-04-20 | 首次发布，基于原 hmdriver2 重构              |\n\n***\n\n## 💡 未来规划\n\n- [ ] 断言/验证机制\n- [ ] 元素截图/高亮\n- [ ] 多设备并行支持\n- [ ] 测试报告生成\n\n***\n\n## 🤝 参与贡献\n\n欢迎提交 Issue 和 Pull Request！\n\n- 🐛 [提交 Issue](https://github.com/ziguiway/HMNextAuto/issues)\n- 📖 [贡献指南](CONTRIBUTING.md)\n\n***\n\n## 🙏 致谢\n\n感谢原项目作者 [@codematrixer](https://github.com/codematrixer) 提供的优秀基础框架！\n\n***\n\n## 📄 License\n\n[MIT License](LICENSE)\n\n***\n\n如果这个项目对你有帮助，请给一个 ⭐️ Star 支持一下！\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fziguiway%2Fhmnextauto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fziguiway%2Fhmnextauto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fziguiway%2Fhmnextauto/lists"}