》》》最近做桌面应用的测试
Inspect.exe 是微软官方的 Windows 桌面 UI 元素定位神器 ,主要用于 Pywinauto、UIAutomation 等自动化测试 ,精准获取控件的 AutomationId、Name、ClassName、ControlType 等定位属性。
一、获取与安装(离线也能用)
Inspect.exe 是 Windows SDK 的一部分,无需安装,直接拷贝使用。
1. 官方获取(有网环境)
-
下载 Windows SDK :只需勾选 Debugging Tools for Windows,其他取消。
-
默认路径(64 位):
Plain
C:\Program Files (x86)\Windows Kits\10\bin\10.0.22621.0\x64\Inspect.exe
2. 离线使用(推荐)
-
在有网电脑找到 Inspect.exe ,直接复制到离线电脑(如
D:\\Tools\\Inspect\.exe)。 -
无需安装依赖,双击即可运行。
二、主界面与核心设置
打开后,界面分三部分:
-
工具栏:模式切换、元素选取、高亮。
-
左侧树视图 (Tree View):UI 元素层级结构。
-
右侧属性面板 (Properties) :控件详细属性(定位关键)。
必做设置(Options 菜单)
-
Always on Top:始终置顶(防止被目标窗口遮住)。
-
UI Automation Mode :必须选(现代应用定位标准)。
-
Show Highlight Rectangle:开启高亮(鼠标悬停时控件出现蓝框)。
三、3 种元素定位方法(实战)
方法 1:鼠标悬停(最常用)
-
点击工具栏 鼠标图标 (Watch Cursor)。
-
鼠标移到目标控件(如按钮、输入框)。
-
自动高亮,右侧立即显示属性。
方法 2:十字准星精确定位
-
点击工具栏 十字图标 (Select Target)。
-
按住鼠标,拖动到目标控件。
-
松开,锁定元素,防止界面变化丢失定位。
方法 3:树形结构遍历(隐藏控件)
-
在左侧 Tree View 展开应用窗口。
-
逐层点击子节点,找到目标控件。
-
右侧查看属性(适合找不到的控件)。
四、关键定位属性(自动化必看)
| 属性 | 说明 | 定位优先级 |
|---|---|---|
| AutomationId | 控件唯一 ID(开发设置) | ★★★★★ 最稳定 |
| Name | 控件显示文本(如 "登录") | ★★★★☆ |
| ControlType | 控件类型(Button/Edit/Window) | ★★★☆☆ |
| ClassName | Win32 类名(如 WindowsForms10.EDIT) | ★★★☆☆ |
| NativeWindowHandle | 窗口句柄(临时定位) | ★★☆☆☆ |
五、Pywinauto 定位实战(复制即用)
python
from pywinauto.application import Application
# 1. 启动应用
app = Application().start("notepad.exe")
dlg = app.UntitledNotepad
# 2. 用 Inspect 获取属性后定位
# 方式1:最佳(AutomationId + ControlType)
edit = dlg.child_window(
auto_id="15", # 从Inspect复制
control_type="Edit"
)
# 方式2:名称定位
btn_save = dlg.child_window(
name="保存(S)...",
control_type="Button"
)
# 方式3:类名定位
edit_box = dlg.child_window(
class_name="Edit",
found_index=0
)
# 3. 操作控件
edit.type_keys("Hello Inspect.exe")
btn_save.click()
六、常见问题
-
找不到控件?
-
确认是 UI Automation 模式。
-
开启 高亮,确认是否选中。
-
用 树形视图 逐层查找。
-
-
属性动态变化?
-
优先用 AutomationId。
-
组合多个属性定位:
-
python
# 组合定位(最稳)
dlg.child_window(name="确定", control_type="Button", class_name="Button")
七、离线环境技巧
-
直接拷贝 Inspect.exe 到离线电脑。
-
先在有网环境熟悉操作,离线直接用。
-
记录常用控件属性,离线编写脚本。
总结
Inspect.exe = Windows 桌面自动化的 "浏览器 F12"
-
获取:拷贝即用,无需安装。
-
设置:置顶 + UI Automation + 高亮。
-
定位:悬停 / 十字 / 树形三选一。
-
属性 :优先 AutomationId。
-
脚本:Pywinauto 复制属性直接定位。