windows 桌面GUI自动化- 18.pywinauto 保存控件菜单树结构print_control_identifiers()

前言

.pywinauto 可以使用 print_control_identifiers() 方法打印控件菜单树结构,这对我们查找控件非常方便。

print_control_identifiers()

查看相关源码

    def print_control_identifiers(self, depth=None, filename=None):
        """
        Prints the 'identifiers'

        Prints identifiers for the control and for its descendants to
        a depth of **depth** (the whole subtree if **None**).

        .. note:: The identifiers printed by this method have been made
               unique. So if you have 2 edit boxes, they won't both have "Edit"
               listed in their identifiers. In fact the first one can be
               referred to as "Edit", "Edit0", "Edit1" and the 2nd should be
               referred to as "Edit2".
        """
       
    print_ctrl_ids = print_control_identifiers
    dump_tree = print_control_identifiers

print_ctrl_ids 和 dump_tree 实现的功能与print_control_identifiers等价,都是调用的print_control_identifiers 方法。
用2个参数

  • depth 查找框架深度,默认全部查找
  • filename 保存本地文件名称

保存本地文件

把打印的内容保存到本地txt,这样查看更方便

from pywinauto import Application


app = Application('uia').start("notepad.exe")
win = app.window(title_re="无标题 - 记事本")
win.print_ctrl_ids(filename="x1.txt")

在windows上运行后文件写入的中文内容有乱码

重新设保存文件默认编码可以解决此问题

from pywinauto import Application
import locale


def getpreferredencoding(do_setlocale = True):
    return "utf-8"


# 设置保存文件编码 "utf-8"
locale.getpreferredencoding = getpreferredencoding
print(locale.getpreferredencoding())

app = Application('uia').start("notepad.exe")
win = app.window(title_re="无标题 - 记事本")
win.print_ctrl_ids(filename="x1.txt")

posted @ 2023-08-26 14:55  上海-悠悠  阅读(774)  评论(1编辑  收藏  举报