當我們想以自動化的方式操作軟件,以提高辦公或測試效率時,有許多成熟的工具,比如針對Web端應用的Selenium、針對移動端應用的Appium。那么,PC端(Windows)桌面應用,又改如何處理呢?
微軟給我們提供了解決方案,即UI Automation ,它能方便我們自動化操作PC端桌面應用程序,微軟是這樣介紹它的:
Microsoft UI Automation is an accessibility framework that enables Windows applications to provide and consume programmatic information about user interfaces (UIs). It provides programmatic access to most UI elements on the desktop. It enables assistive technology products, such as screen readers, to provide information about the UI to end users and to manipulate the UI by means other than standard input. UI Automation also allows automated test scripts to interact with the UI.
美中不足的是,該工具支持C/C++調用。對於以Python為常用語言的我來說,則需要想想辦法。恰好,已經有Python庫為我們封裝了微軟UI Automation的API,即uiautomation庫。為了初步介紹如何使用該庫,我們將解決一個實際問題:如何獲取CMD窗口中所打印的文字信息?
首先,安裝uiautomation庫。
pip install uiautomation
接下來,調用uiautomation庫提供的方法去定位CMD窗口中的文字信息。這里有一個問題,我們如何去定位CMD窗口?微軟提供了UI Spy供開發者使用,界面如下所示,通過它能夠快速獲取窗口或控件的屬性信息,其中就包括標識信息。
在UI Spy中找到CMD窗口下的文檔控件,可以看到右邊屬性欄顯示了Text信息,該Text信息就是我們要的目標文字。只要通過uiautomation庫獲取該Text信息即可。
uiautomation庫的具體用法可以查看該庫作者寫的教程,下面是我給出的示例,用於獲取CMD窗口中打印的文字信息。
import uiautomation cmd_window = uiautomation.WindowControl(searchDepth=1, Name='管理員: 命令提示符', AutomationId='Console Window') cmd_text = cmd_window.DocumentControl(searchDepth=1).GetTextPattern().DocumentRange.GetText() print(cmd_text)
運行結果:
D:\>ping baidu.com 正在 Ping baidu.com [220.181.38.251] 具有 32 字節的數據: 來自 220.181.38.251 的回復: 字節=32 時間=49ms TTL=47 來自 220.181.38.251 的回復: 字節=32 時間=52ms TTL=47 來自 220.181.38.251 的回復: 字節=32 時間=49ms TTL=47 來自 220.181.38.251 的回復: 字節=32 時間=52ms TTL=47 220.181.38.251 的 Ping 統計信息: 數據包: 已發送 = 4,已接收 = 4,丟失 = 0 (0% 丟失), 往返行程的估計時間(以毫秒為單位): 最短 = 49ms,最長 = 52ms,平均 = 50ms D:\>
參考資料
- https://docs.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32
- https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/master/readme_cn.md