桌面應用自動化python——uiautomation API 如何找元素


     本文主要用到一個uiautomation的開源框架,是一個咱們中國人寫的,支持MFC,Windows Forms,WPF,Metro,Qt界面;此文主要是自己的個人總結,開源作者原文:http://www.cnblogs.com/Yinkaisheng/p/3444132.html

gethub地址: https://github.com/yinkaisheng/Python-UIAutomation-for-Windows

        此自動化的主要思想是利用此框架抓取到程序的各種句柄,然后對句柄執行各種操作。

 

一、uiautomation方法

1、WindowContrl(searchDepth,ClassName,SubName)          查找窗口中的程序,如果有中文則需用Unicode;可用window.Exists(maxSearchSeconds)來判斷此窗口是否存在;

2、EditControl(searchFromControl)                 查找編輯位置,找到后可用DoubleClick()來改變電腦的focus;edit.SetValue("string")輸入值;

3、Win32API.SendKeys("string")                      如果已在編輯位置,則可用此方法來輸入值,{Ctrl}為ctrl鍵,其他類似;{@  8}格式可輸入8個@,對於數字也可實現此功能,但對於字母不能...;

4、MenuItemControl(searchFromControl,Name)                   查找菜單按鈕;

5、ComboBoxControl(searchFromControl,AutomationI)       查找下拉框,然后在此基礎上用Select("name")方法來選擇需要的選項;

6、BottonControl(searchFromControl,Name,SubName)        查找按鈕;

7、automation.FindControl(firefoxWindow,

                           lambda c:(isinstance(c, automation.EditControl) or isinstance(c, automation.ComboBoxControl)) and c.Name == 'Enter your search term'

                           ) 按條件搜索handle

 

二、對找到句柄常用操作

Click()            點擊;

RighClik()       右鍵點擊;

SendKeys()     發送字符;

SetValue()      傳值,一般對EditControl用;

 

三、對windows程序常用操作

subprocess.Popen('Name')    用進程打開程序;

window.Close()            關閉窗口;

window.SetActive()           使用;

window.SetTopMost()       設置為頂層

window.ShowWindow(uiautomation.ShowWindow.Maximize)  窗口最大化

window.CaptureToImage('Notepad.png')  截圖;

 

uiautomation.Win32API.PressKey(uiautomation.Keys.VK_CONTROL)    按住Ctrl鍵

uiautomation.Win32API.ReleaseKey(uiautomation.Keys.VK_CONTROL) 釋放Ctrl鍵

automation.GetConsoleWindow()      #return console window that runs python,打開控制台

automation.Logger.ColorfulWriteLine('\nI will open <Color=Green>Notepad</Color> and <Color=Yellow>automate</Color> it. Please wait for a while.')  控制台傳值(彩色字體),普通傳值用WriteLine;

automation.ShowDesktop() 顯示桌面;

 

四、句柄的抓取

直接運行automation模塊枚舉窗口時,支持下列參數(從doc窗口運行automation.py程序 ):

-t intValue     延遲枚舉時間,單位秒

-r                  從樹的根部枚舉,如果不指定,從當前窗口枚舉

-d intValue    枚舉控件樹的的深度,如果不指定,枚舉整個樹

-f                  從焦點控件枚舉,如果不指定,從當前窗口枚舉

-c                  從光標下的控件枚舉,如果不指定,從當前窗口枚舉

-a                  獲取光標下控件及其所有父控件

 

-n                 顯示控件的完整Name, 如果不指定,只顯示前30個字符

-m                顯示控件更多屬性,默認只顯示控件的四個屬性

示例:

automation.py c –t3            // 3秒后枚舉當前窗口所有控件

automation.py c –d2 –t3         // 3秒后枚舉當前窗口前三層控件

automation.py c –r –d1 –t0 -n    // 0秒后從根部枚舉前兩層控件,並顯示控件完整名稱

automation.py c –c –t3             // 3秒后顯示鼠標光標下面的控件信息

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM