def BatchRename(): foxitWindow = automation.WindowControl(searchDepth=1, ClassName='classFoxitReader') foxitWindow.ShowWindow(automation.ShowWindow.ShowMaximized) foxitWindow.SetActive() automation.Logger.Log(foxitWindow.Name[:-len(' - Foxit Reader')] + '\n') time.sleep(1) automation.SendKeys('{Ctrl}0') time.sleep(0.5) editToolBar = automation.ToolBarControl(searchFromControl=foxitWindow, AutomationId='59583', Name='Caption Bar') if editToolBar.Exists(0, 0): editToolBar.Click(0.96, 0.5) time.sleep(0.5) automation.SendKeys('{Alt}y') time.sleep(0.5) editToolBar = automation.ToolBarControl(searchFromControl=foxitWindow, AutomationId='60683', Name='Caption Bar') if editToolBar.Exists(0, 0): editToolBar.Click(0.96, 0.5) time.sleep(0.5) automation.SendKeys('{Alt}y') time.sleep(0.5) paneWindow = automation.WindowControl(searchFromControl=foxitWindow, AutomationId='65280') bookmarkPane = automation.PaneControl(searchFromControl=paneWindow, searchDepth=1, foundIndex=1) l, t, r, b = bookmarkPane.BoundingRectangle #bookmarkButton = automation.ButtonControl(searchFromControl= bookmarkPane, Name = '书签') # can't find, but automation -a can find it, why if bookmarkPane.Name == '书签': if r - l < 40: bookmarkButton = automation.ControlFromPoint(l + 10, t + 40) if bookmarkButton.Name == '书签': bookmarkButton.Click(simulateMove=False) else: bookmarkButton = automation.ControlFromPoint(l + 10, t + 40) if bookmarkButton.Name == '书签': bookmarkButton.Click(simulateMove=False) tree = automation.TreeControl(searchFromControl=foxitWindow, ClassName='SysTreeView32') childItems = tree.GetChildren() bookMarks = [] depth = 1 for treeItem in childItems: if treeItem.ControlType == automation.ControlType.TreeItemControl: RenameTreeItem(tree, treeItem, bookMarks, depth) fout = open('rename_pdf_bookmark.txt', 'wt', encoding='utf-8') depth = 1 for bookMark in bookMarks: DumpBookMark(fout, bookMark, depth) fout.close() if Renamed: automation.Logger.Log('rename pdf: ' + foxitWindow.Name) automation.SendKeys('{Ctrl}s') time.sleep(0.5) while '*' in foxitWindow.Name: time.sleep(0.5)
def fill_in_conference_id(self, conference_id): """暂时改变不了值""" self.login_windows.TextControl(searchDepth=2, Name="加入会议").Click() x, y = auto.GetCursorPos() # Normal PC auto.Click(x + 55, y + 95) # Hihg DPI auto.Click(x + 45, y + 75) auto.SendKeys("{BACK}" * 40) auto.SendKeys(conference_id)
def gain_session(self, name): '''获取点击暂存以后得到的session''' time.sleep(5) if '退回修改' in name: for i in range(1, 3): automation.SendKeys('{Down}') time.sleep(5) pyautogui.screenshot(IMGSRC) imgobj = r'\thyj.jpg' imsrc = ac.imread(IMGSRC) imobj = ac.imread(file + imgobj) match_result = ac.find_template(imsrc, imobj, 0.7) if match_result: REDIS_GZ.hset('specify_account_session', {'session': 'true'}) result = REDIS_GZ.hget('specify_account_yctAppNo_page') if result['total'] == result['getpage']: return 2 automation.SendKeys('{Ctrl}k{Ctrl}k') time.sleep(2) automation.SendKeys( 'http://yct.sh.gov.cn/portal_yct/webportal/handle_progress.do?x=12{Enter}' ) return 1 else: self.restart_login = True return 1 elif '填报成功' in name: time.sleep(5) pyautogui.screenshot(IMGSRC) # time.sleep(5) imgobj = r'\tbcg.jpg' imsrc = ac.imread(IMGSRC) imobj = ac.imread(file + imgobj) match_result = ac.find_template(imsrc, imobj, 0.8) if match_result: REDIS_GZ.hset('specify_account_session', {'session': 'true'}) result = REDIS_GZ.hget('specify_account_yctAppNo_page') if result['total'] == result['getpage']: return 2 automation.SendKeys('{Ctrl}k{Ctrl}k') time.sleep(2) automation.SendKeys( 'http://yct.sh.gov.cn/portal_yct/webportal/handle_progress.do?x=12{Enter}' ) time.sleep(5) return 1 else: self.restart_login = True return 1
def walk(): wiresharkWindow = None for win in auto.GetRootControl().GetChildren(): if win.ClassName == 'MainWindow' and win.AutomationId == 'MainWindow': if win.ToolBarControl( AutomationId='MainWindow.displayFilterToolBar').Exists( 0, 0): wiresharkWindow = win break if not wiresharkWindow: auto.Logger.WriteLine('Can not find Wireshark', auto.ConsoleColor.Yellow) return console = auto.GetConsoleWindow() if console: sx, sy = auto.GetScreenSize() tp = console.GetTransformPattern() tp.Resize(sx, sy // 4) tp.Move(0, sy - sy // 4 - 50) console.SetTopmost() wiresharkWindow.SetActive(waitTime=0.1) wiresharkWindow.Maximize() auto.Logger.ColorfullyWriteLine('Press <Color=Cyan>F1</Color> to stop', auto.ConsoleColor.Yellow) tree = wiresharkWindow.TreeControl(searchDepth=4, ClassName='PacketList', Name='Packet list') rect = tree.BoundingRectangle tree.Click(y=50, waitTime=0.1) auto.SendKeys('{Home}', waitTime=0.1) columnCount = 0 treeItemCount = 0 for item, depth in auto.WalkControl(tree): if isinstance(item, auto.HeaderControl): columnCount += 1 auto.Logger.Write(item.Name + ' ') elif isinstance(item, auto.TreeItemControl): if treeItemCount % columnCount == 0: auto.Logger.Write('\n') time.sleep(0.1) treeItemCount += 1 auto.Logger.Write(item.Name + ' ') if item.BoundingRectangle.bottom >= rect.bottom: auto.SendKeys('{PageDown}', waitTime=0.1) if auto.IsKeyPressed(auto.Keys.VK_F1): auto.Logger.WriteLine('\nF1 pressed', auto.ConsoleColor.Yellow) break
def clear_text(self, edit_control): try: # edit_control.Click() auto.SendKeys("{Ctrl}a{Delete}") logger.info("{}_edit_control中内容清除成功") except: logger.exception("{}_edit_control中内容清除失败")
def append_password(self, password): self.login_windows.TextControl(searchDepth=2, Name="加入会议").Click() x, y = auto.GetCursorPos() # Normal PC auto.Click(x + 55, y + 95) # Hihg DPI auto.Click(x + 45, y + 75) auto.SendKeys(password)
def lddb(self): # 判断页数是否是相同不相同则继续点击下一页 time.sleep(5) name = REDIS_GZ.hget('specify_account_yctAppNo_page') for i in range(1, 3): time.sleep(2) automation.SendKeys('{Down}') for i in range(1, 6): for x in range(1, 8): res = REDIS_GZ.hget('specify_account_session') automation.SendKeys('{Down}') if 'false' == res['session']: pyautogui.screenshot(IMGSRC) imgobj = file + r'\th.jpg' imsrc = ac.imread(IMGSRC) imobj = ac.imread(imgobj) match_result = ac.find_template(imsrc, imobj, 0.8) if match_result: automation.HyperlinkControl(Depth=17, Name='退回修改', foundIndex=i).Click() if self.gain_session(name='退回修改') == 2: return 1 elif self.restart_login == True: return 1 else: self.lddb() imgobj = file + r'\txcg.jpg' imobj = ac.imread(imgobj) match_result = ac.find_template(imsrc, imobj, 0.8) if match_result: automation.HyperlinkControl(Depth=17, Name='填报成功(查看详情)').Click() if self.gain_session(name='填报成功') == 2: return 1 elif self.restart_login == True: return 1 else: self.lddb() else: continue if name['getpage'] == name['total']: return 1 else: return
def run_step(self): for process_bar in ['login', 'trace_list', 'detail', 'changeaccount']: try: eval('self.{}()'.format(process_bar)) except Exception as e: print(e) if self.restart_login: automation.SendKeys('{Ctrl}k{Ctrl}k') automation.SendKeys('%s{Enter}' % ( 'http://yct.sh.gov.cn/portal_yct/webportal/handle_progress.do?x=11' )) return REDIS_GZ.hset('specify_account_yctAppNo_page', { 'getpage': '-1', 'total': '-2' }) return 'success'
def yzdl(self): '''用于验证登录匹配是否有办理进度跟踪字样,如果有返回1说明登录成功''' time.sleep(5) result = automation.ButtonControl(Depth=3, Name='继续') if automation.WaitForExist(result, 5): automation.SendKeys('{Enter}') time.sleep(5) automation.SendKeys('{F6}') automation.SendKeys( 'http://yct.sh.gov.cn/portal_yct/webportal/handle_progress.do?x=12' ) automation.SendKeys('{Enter}') time.sleep(5) result = automation.CustomControl(Depth=9, Name='办理进度跟踪') if automation.WaitForExist(result, 5): return 1 else: self.restart_login = True
def RenameTreeItem(tree, treeItem, bookMarks, depth, removeChapter=True): treeItem.ScrollIntoView() if depth > TreeDepth: return name = treeItem.Name if not name.strip(): return newName = RenameFunction(name, removeChapter) if newName.startswith('Appendix'): removeChapter = False bookMark = BookMark(name, newName) bookMarks.append(bookMark) if newName != name: global Renamed Renamed = True time.sleep(0.1) treeItem.RightClick(simulateMove=False) # FoxitReader书签右键菜单(BCGPToolBar,非Windows菜单)弹出后,枚举不到菜单,但从屏幕点上ControlFromPoint能获取到菜单, todo # 采用特殊处理获取重命名菜单 time.sleep(0.2) x, y = automation.Win32API.GetCursorPos() menuItem = automation.ControlFromPoint(x + 2, y + 2) if menuItem.ControlType == automation.ControlType.MenuItemControl: #鼠标右下方弹出菜单 while not (menuItem.Name == '重命名(R)' or menuItem.Name == 'Rename'): y += 20 menuItem = automation.ControlFromPoint(x + 2, y) if menuItem.ControlType != automation.ControlType.MenuItemControl: break else: #鼠标右上方弹出菜单 menuItem = automation.ControlFromPoint(x + 2, y - 2) while not (menuItem.Name == '重命名(R)' or menuItem.Name == 'Rename'): y -= 20 menuItem = automation.ControlFromPoint(x + 2, y) if menuItem.ControlType != automation.ControlType.MenuItemControl: break if menuItem.ControlType != automation.ControlType.MenuItemControl: automation.Logger.Log('this pdf not support editing') exit(0) menuItem.Click(simulateMove=False) edit = automation.EditControl(searchFromControl=tree, searchDepth=1) edit.SetValue(newName) automation.SendKeys('{Enter}') automation.Logger.Write('rename: ') automation.Logger.WriteLine(name, automation.ConsoleColor.Green) automation.Logger.Write(' to: ') automation.Logger.WriteLine(newName, automation.ConsoleColor.Green) if depth + 1 > TreeDepth: return treeItem.Expand() childItems = treeItem.GetChildren() if childItems: treeItem.Expand() for child in childItems: RenameTreeItem(tree, child, bookMark.children, depth + 1, removeChapter)
def end_meeting(): automation.SendKeys('{Alt}q') time.sleep(1) window = automation.WindowControl(searchDepth=1, ClassName='zLeaveWndClass') for control, depth in automation.WalkTree(window, getFirstChild=GetFirstChild, getNextSibling=GetNextSibling, includeTop=False, maxDepth=2): if str(control).find("End Meeting for All") > 0: control.Click(simulateMove = False) exit(0)
def test_search_img(): currentPath = os.path.abspath(os.path.dirname(__file__)) config = configparser.ConfigParser() config.read(os.path.join(currentPath, 'config.ini')) # 1. start Chrome and set to maximized driver = webdriver.Chrome(executable_path='./chromedriver.exe') driver.maximize_window() driver.implicitly_wait(10) # 2. goto 'https://www.baidu.com/' # driver.get('https://www.google.com/imghp?hl=zh-CN&tab=wi&ogbl') driver.get('https://www.baidu.com/') driver.find_element_by_class_name('soutu-btn').click() time.sleep(5) # 3. upload an image and start searching uia.ButtonControl(Name='选择文件').Click() window = uia.WindowControl(ClassName='#32770') filePath = os.path.join(currentPath, 'pythontab.jpg') uia.SendKeys(filePath) uia.ButtonControl(AutomationId='1').Click() time.sleep(10) driver.save_screenshot('1.png') # 4. get the target search result and validate it target = int(config.get('CheckPoint', 'VISIT_RESULT')) img = driver.find_element_by_css_selector( 'div.graph-row.graph-same-list > div:nth-child({0}) > div > a > div.graph-same-list-img > img' .format(target)) js4 = "arguments[0].scrollIntoView();" driver.execute_script(js4, img) img.screenshot('./tempfile/1.jpg') img1 = Image.open('./tempfile/1.jpg') img1.thumbnail((128, 128)) img2 = Image.open('./pythontab.jpg') img2.thumbnail((128, 128)) h1 = img1.histogram() h2 = img2.histogram() diff = math.sqrt( reduce(operator.add, list(map(lambda a, b: (a - b)**2, h1, h2))) / len(h1)) assert diff < 100 img1.close() img2.close() # 5. quite the test application time.sleep(5) driver.quit()
def changeaccount(self): time.sleep(2) try: automation.SendKeys('{Ctrl}k{Ctrl}k') time.sleep(2) automation.SendKeys( 'http://yct.sh.gov.cn/portal_yct/webportal/handle_progress.do?x=12{Enter}' ) except Exception as e: print(e) else: time.sleep(5) pyautogui.screenshot(IMGSRC) imgobj = file + r'\tc.jpg' imsrc = ac.imread(IMGSRC) imobj = ac.imread(imgobj) match_result = ac.find_template(imsrc, imobj, 0.8) if match_result: automation.HyperlinkControl(Depth=12, Name='退出').Click() time.sleep(5) REDIS_GZ.hset('specify_account_session', {'session': 'false'}) automation.HyperlinkControl(Depth=11, Name='账号密码登录').Click() else: self.restart_login = True
def main(): automation.Logger.WriteLine('请把鼠标放在QQ群聊天窗口中的一个成员上面,3秒后获取\n') time.sleep(3) listItem = automation.ControlFromCursor() if listItem.ControlType != automation.ControlType.ListItemControl: automation.Logger.WriteLine('没有放在群成员上面,程序退出!') return consoleWindow = automation.GetConsoleWindow() if consoleWindow: consoleWindow.SetActive() qqWindow = listItem.GetTopWindow() list = listItem.GetParentControl() allListItems = list.GetChildren() for listItem in allListItems: automation.Logger.WriteLine(listItem.Name) answer = 'y' if answer.lower() == 'y': automation.Logger.WriteLine('\n3秒后开始获取QQ群成员详细资料,您可以一直按住F10键暂停脚本') time.sleep(3) qqWindow.SetActive() #确保群里第一个成员可见在最上面 left, top, right, bottom = list.BoundingRectangle while allListItems[0].BoundingRectangle[1] < top: automation.Win32API.MouseClick(right - 5, top + 20) for listItem in allListItems: if listItem.ControlType == automation.ControlType.ListItemControl: if automation.Win32API.IsKeyPressed(automation.Keys.VK_F10): if consoleWindow: consoleWindow.SetActive() input('\n您暂停了脚本,按Enter继续\n') qqWindow.SetActive() listItem.RightClick() menu = automation.MenuControl(searchDepth= 1, ClassName = 'TXGuiFoundation') menuItems = menu.GetChildren() for menuItem in menuItems: if menuItem.Name == '查看资料': menuItem.Click() break automation.Logger.WriteLine('eachpersonstart') automation.Logger.WriteLine(listItem.Name, automation.ConsoleColor.Green) automation.Logger.WriteLine(GetPersonDetail()) listItem.Click() automation.SendKeys('{Down}')
def get_allpatients(self): self.scroll_top() patientsdict = {} firstrow_parent = self.find(**self.firstrow_parent) firstrow = self.find(searchFromControl=firstrow_parent, **self.firstrow) firstrow.Click() index = 1 patientsdict["index" + str(index)] = self.find( searchFromControl=firstrow, **self.patientname).Name nextrow = firstrow.GetNextSiblingControl() while nextrow: auto.SendKeys("{DOWN}") index += 1 patientname = self.find(searchFromControl=nextrow, **self.patientname).Name patientsdict["index" + str(index)] = patientname nextrow = nextrow.GetNextSiblingControl() auto.WheelUp(100) return patientsdict
def join_a_meeting_from_panel_with_password_one_line( self, password, mute="false"): self.go_to_meeting_page() sleep(10) self.hexMeetHJTWindow.GroupControl( searchDepth=1, AutomationId="CHomeDlg.m_pWgtContext").TextControl( searchDepth=9, Name="加入会议").Click() sleep(1) self.hexMeetHJTWindow.WindowControl( searchDepth=1, ClassName="ev_app::views::CJoinConfDlg").TextControl( searchDepth=2, Name="加入会议").Click() self.mute_audio(mute) self.mute_camera(mute) # 通过移动鼠标到会议号码后面并添加密码 x, y = auto.GetCursorPos() # auto.Click(x+50, y+50) # hig DPI auto.Click(x + 40, y + 40) auto.SendKeys("*" + password + "{ENTER}")
def open_newtab(self, username, password="******", url=None): import uiautomation num = 12 for i in range(num): uiautomation.SendKeys("{Ctrl}(t)") handles = self.driver.window_handles current_handle = self.driver.current_window_handle k = 0 for handle in handles: if current_handle == handle: continue else: self.driver.switch_to.window(handle) self.login_rcs(username[k], password, url) #self.driver.switch_to.default_content() sleep(1) self.elements_method('xpath', HomePage.xpath_fast, 'click') sleep(1) BaseMethod.web_open_fast(1) k += 1
def pjurl(self): '''控制鼠标到url栏,删除,重写,按enter键''' specify_account_yctAppNo = REDIS_GZ.hget('specify_account_yctAppNo') if specify_account_yctAppNo: for yctAppNo in specify_account_yctAppNo: if '退回修改' in specify_account_yctAppNo[yctAppNo]: automation.SendKeys('{Ctrl}k{Ctrl}k') automation.SendKeys('%s{Enter}' % ( 'http://yct.sh.gov.cn/bizhallnz_yctnew/apply/appendix/print?yctAppNo={}' .format(yctAppNo))) time.sleep(10) break elif '填报成功' in specify_account_yctAppNo[yctAppNo]: automation.SendKeys('{Ctrl}k{Ctrl}k') automation.SendKeys('%s{Enter}' % ( 'http://yct.sh.gov.cn/bizhallnz_yctnew/apply/appendix/print?yctAppNo={}' .format(yctAppNo))) time.sleep(10) results = REDIS_GZ.hget('specify_account_tbcg_' + yctAppNo) for result in results: if len(result) > 15: id_, app_no = result.split('^') automation.SendKeys('{Ctrl}k{Ctrl}k') automation.SendKeys('%s{Enter}' % ( 'http://yct.sh.gov.cn/bizhallnz_yctnew/apply/appendix/content_special?id=-{}&p=1&app_no={}&papers={}&yctAppNo={}' .format(id_, app_no, result, yctAppNo))) time.sleep(10) else: automation.SendKeys('{Ctrl}k{Ctrl}k') automation.SendKeys('%s{Enter}' % ( 'http://yct.sh.gov.cn/bizhallnz_yctnew/apply/appendix/content?id=-{}&appendixStatus=&isPrint=1&p=1&papers={}&yctAppNo={}' .format(result, result, yctAppNo))) time.sleep(10) break else: return 1
def Analyze(sampleRate=90000, beginNo=0, maxPackets=0xFFFFFFFF, calculateLost=False): wireSharkWindow = automation.WindowControl(searchDepth=1, ClassName='Qt5QWindowIcon') if wireSharkWindow.Exists(0, 0): wireSharkWindow.SetActive() else: automation.Logger.WriteLine('can not find wireshark', automation.ConsoleColor.Yellow) return tree = automation.TreeControl(searchFromControl=wireSharkWindow, searchDepth=4, SubName='Packet list') left, top, right, bottom = tree.BoundingRectangle tree.Click(10, 30) automation.SendKeys('{Home}{Ctrl}{Alt}4') time.sleep(0.5) tree.Click(10, 30) headers = [] headerFunctionDict = { 'No': int, 'Time': float, 'Source': str, 'Destination': str, 'Protocol': str, 'Length': int, 'Info': str, } index = 0 packets = [] for item, depth in automation.WalkTree( tree, getFirstChildFunc=lambda c: c.GetFirstChildControl(), getNextSiblingFunc=lambda c: c.GetNextSiblingControl()): if isinstance(item, automation.HeaderControl): headers.append(item.Name.rstrip('.')) elif isinstance(item, automation.TreeItemControl): if index == 0: if len(packets) >= maxPackets: break packet = PacketInfo() name = item.Name packet.__dict__[headers[index]] = headerFunctionDict[ headers[index]](name) if headers[index] == 'Info': startIndex = name.find('Seq=') if startIndex > 0: endIndex = name.find(' ', startIndex) packet.Seq = int(name[startIndex + 4:endIndex].rstrip(',')) startIndex = name.find('Time=') if startIndex > 0: endIndex = name.find(' ', startIndex) packet.TimeStamp = int(name[startIndex + 5:endIndex].rstrip(',')) if packet.No >= beginNo: packets.append(packet) automation.Logger.WriteLine( 'No: {0[No]:<10}, Time: {0[Time]:<10}, Protocol: {0[Protocol]:<6}, Length: {0[Length]:<6}, Info: {0[Info]:<10},' .format(packet.__dict__)) index = (index + 1) % len(headers) if item.BoundingRectangle[3] >= bottom: automation.SendKeys('{PageDown}') time.sleep(0.1) automation.Logger.WriteLine('\n----------\nAnalyze Result:') seq = packets[0].Seq - 1 lostSeqs = [] framePackets = [] lastTimeStamp = -1 for p in packets: seq += 1 if seq != p.Seq: lostSeqs.extend(range(seq, p.Seq)) seq = p.Seq if lastTimeStamp < 0: framePackets.append(p) else: if lastTimeStamp == p.TimeStamp: framePackets[-1] = p else: framePackets.append(p) lastTimeStamp = p.TimeStamp lastTimeStamp = -1 lastTime = -1 totalDiff = 0 frameCount = 0 for p in framePackets: if lastTimeStamp < 0: automation.Logger.WriteLine( 'No: {0[No]:<8}, Time: {0[Time]:<10}, Protocol: {0[Protocol]}, Length: {0[Length]:<6}, TimeStamp: {0[TimeStamp]:<15}' .format(p.__dict__)) else: diffTimeStamp = p.TimeStamp - lastTimeStamp frameCount += 1 totalDiff += diffTimeStamp sumTime = p.Time - framePackets[0].Time sumTimeFromTimeStamp = (p.TimeStamp - framePackets[0].TimeStamp) / sampleRate automation.Logger.WriteLine( 'No: {0[No]:<8}, Time: {0[Time]:<10}, Protocol: {0[Protocol]}, Length: {0[Length]:<6}, TimeStamp: {0[TimeStamp]:<15}, 帧时间戳差值: {1:<6}, 帧实际时间差值: {2:<10.6f}, 实际接收时间: {3:<10.6f}, 时间戳时间: {4:<10.6f}, 提前时间:{5:<10.6f}' .format(p.__dict__, diffTimeStamp, p.Time - lastTime, sumTime, sumTimeFromTimeStamp, sumTimeFromTimeStamp - sumTime)) lastTime = p.Time lastTimeStamp = p.TimeStamp if frameCount: averageDiff = totalDiff // frameCount frameCount += 1 seqCount = packets[-1].Seq - packets[0].Seq + 1 totalTimeFromTimeStamp = (framePackets[-1].TimeStamp - framePackets[0].TimeStamp) / sampleRate realTime = framePackets[-1].Time - framePackets[0].Time if calculateLost: automation.Logger.WriteLine( '\n包总数: {0}, 帧数: {1}, 实际帧率:{2:.2f}, 平均时间戳: {3}, 总时间: {4:.6f}, 时间戳总时间: {5:.6f}, 丢包数: {6}({7:.2f}%), 丢包序号: {8}' .format(len(packets), frameCount, frameCount / realTime, averageDiff, realTime, totalTimeFromTimeStamp, len(lostSeqs), len(lostSeqs) / seqCount, lostSeqs)) else: automation.Logger.WriteLine( '\n包总数: {0}, 帧数: {1}, 实际帧率:{2:.2f}, 平均时间戳: {3}, 总时间: {4:.6f}, 时间戳总时间: {5:.6f}' .format(len(packets), frameCount, frameCount / realTime, averageDiff, realTime, totalTimeFromTimeStamp))
# time.sleep(5) # if self.gain_session(name='填报成功') == 2: # print('192') # return 1 # elif self.restart_login == True: # print('190行') # return 1 # else: # print(193) # time.sleep(5) # self.lddb() # else: # print(196) # continue # # if name['getpage'] == name['total']: # if name['getpage'] == '3': # print('205') # return 1 # else: # print(208) # return # else: # self.restart_login = True # print('204行') # return 1 # import time time.sleep(5) import uiautomation as automation automation.SendKeys('{End}')
def copy_from_clipboard(self): try: auto.SendKeys("{Ctrl}v") logger.info("从剪切板复制内容成功") except: logger.exception("从剪切板复制内容失败")
def DemoCN(): """for Chinese language""" thisWindow = auto.GetConsoleWindow() auto.Logger.ColorfullyWrite( '我将运行<Color=Cyan>cmd</Color>并设置它的<Color=Cyan>屏幕缓冲区</Color>使<Color=Cyan>cmd</Color>一行能容纳很多字符\n\n' ) time.sleep(3) auto.SendKeys('{Win}r') while not isinstance(auto.GetFocusedControl(), auto.EditControl): time.sleep(1) auto.SendKeys('cmd{Enter}') cmdWindow = auto.WindowControl(RegexName='.+cmd.exe') cmdWindow.TitleBarControl().RightClick() auto.SendKey(auto.Keys.VK_P) optionWindow = cmdWindow.WindowControl(SubName='属性') optionWindow.TabItemControl(SubName='选项').Click() optionTab = optionWindow.PaneControl(SubName='选项') checkBox = optionTab.CheckBoxControl(AutomationId='103') if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On: checkBox.Click() checkBox = optionTab.CheckBoxControl(AutomationId='104') if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On: checkBox.Click() optionWindow.TabItemControl(SubName='布局').Click() layoutTab = optionWindow.PaneControl(SubName='布局') layoutTab.EditControl(AutomationId='301').GetValuePattern().SetValue('300') layoutTab.EditControl( AutomationId='303').GetValuePattern().SetValue('3000') layoutTab.EditControl(AutomationId='305').GetValuePattern().SetValue('140') layoutTab.EditControl(AutomationId='307').GetValuePattern().SetValue('30') optionWindow.ButtonControl(AutomationId='1').Click() cmdWindow.SetActive() rect = cmdWindow.BoundingRectangle auto.DragDrop(rect.left + 50, rect.top + 10, 50, 30) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '我将运行<Color=Cyan>记事本</Color>并输入<Color=Cyan>Hello!!!</Color>\n\n') time.sleep(3) subprocess.Popen('notepad') notepadWindow = auto.WindowControl(searchDepth=1, ClassName='Notepad') cx, cy = auto.GetScreenSize() notepadWindow.MoveWindow(cx // 2, 20, cx // 2, cy // 2) time.sleep(0.5) notepadWindow.EditControl().SendKeys('Hello!!!', 0.05) time.sleep(1) dir = os.path.dirname(__file__) scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py')) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '运行"<Color=Cyan>automation.py -h</Color>"显示帮助\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '运行"<Color=Cyan>automation.py -r -d1</Color>"显示所有顶层窗口, 即桌面的子窗口\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '运行"<Color=Cyan>automation.py -c</Color>"显示鼠标光标下的控件\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '运行"<Color=Cyan>automation.py -a</Color>"显示鼠标光标下的控件和它的所有父控件\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '运行"<Color=Cyan>automation.py</Color>"显示当前激活窗口和它的所有子控件\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.EditControl().Click() time.sleep(3) cmdWindow.SetActive(waitTime=2) time.sleep(3) thisWindow.SetActive() auto.Logger.WriteLine('演示结束,按Enter退出', auto.ConsoleColor.Green) input()
def DemoEN(): """for other language""" thisWindow = auto.GetConsoleWindow() auto.Logger.ColorfullyWrite('I will run <Color=Cyan>cmd</Color>\n\n') time.sleep(3) auto.SendKeys('{Win}r') while not isinstance(auto.GetFocusedControl(), auto.EditControl): time.sleep(1) auto.SendKeys('cmd{Enter}') cmdWindow = auto.WindowControl(SubName='cmd.exe') rect = cmdWindow.BoundingRectangle auto.DragDrop(rect.left + 50, rect.top + 10, 50, 10) thisWindow.SetActive() auto.Logger.ColorfullyWrite( 'I will run <Color=Cyan>Notepad</Color> and type <Color=Cyan>Hello!!!</Color>\n\n' ) time.sleep(3) subprocess.Popen('notepad') notepadWindow = auto.WindowControl(searchDepth=1, ClassName='Notepad') cx, cy = auto.GetScreenSize() notepadWindow.MoveWindow(cx // 2, 20, cx // 2, cy // 2) time.sleep(0.5) notepadWindow.EditControl().SendKeys('Hello!!!', 0.05) time.sleep(1) dir = os.path.dirname(__file__) scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py')) thisWindow.SetActive() auto.Logger.ColorfullyWrite( 'run "<Color=Cyan>automation.py -h</Color>" to display the help\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() auto.Logger.ColorfullyWrite( 'run "<Color=Cyan>automation.py -r -d1</Color>" to display the top level windows, desktop\'s children\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() auto.Logger.ColorfullyWrite( 'run "<Color=Cyan>automation.py -c</Color>" to display the control under mouse cursor\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() auto.Logger.ColorfullyWrite( 'run "<Color=Cyan>automation.py -a</Color>" to display the control under mouse cursor and its ancestors\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() auto.Logger.ColorfullyWrite( 'run "<Color=Cyan>automation.py</Color>" to display the active window\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.EditControl().Click() time.sleep(3) cmdWindow.SetActive(waitTime=2) time.sleep(3) thisWindow.SetActive() auto.Logger.WriteLine('press Enter to exit', auto.ConsoleColor.Green) input()
3. 在Windows的UIAutomation中, 所能够控制的控件一定是属于某种Control类型的, 比如一个Window就属于WindowControl WindowControl里面包含的其它控件, 比如notepad的Menu,就属于MenuBarControl ''' note = auto.WindowControl(searchDepth=1, ClassName="Notepad") note.SetActive() # edit = note.EditControl() # 查找notepad window下的第一个edit控件, 不指定任何条件的话默认就是返回找到的第一个控件 ''' 而不同的Control类型会支持不同的操作, UIAutomation中, 把一些相同的操作包装成为了Pattern, 一种Control能够支持不同的Pattern, 而不同的Control也可以支持同一种Pattern(表示这些Control都支持对它进行相同的操作) 比如下面的EditControl就支持ValuePattern, 就可以使用ValuePattern包装的方法去操作这个Control ''' edit_value_pattern = edit.GetValuePattern() # 可以使用edit.GetPattern(auto.PatternId.ValuePattern) edit_value_pattern.SetValue("Hello World") edit.SendKeys('{Ctrl}{End}{Enter}By Elden') # 当然可以使用模拟按键的方法来输入文字, 但这个方法主要还是用来向控件发送快捷键 title_bar = note.TitleBarControl() # 只有一个title bar # title bar上有三个按键, 最小化,最大化与关闭, 指定获得找到的ButtonControl的第2个 max_size = title_bar.ButtonControl(foundIndex=2) max_size.Click() # 使用控件名字来查找控件(一般来说控件名字都与控件上显示出来的文字一样的) close = title_bar.ButtonControl(Name='Close') close.Click() auto.SendKeys('{Alt}n')
def AnalyzeUI(sampleRate=90000, payload=96, beginNo=0, maxPackets=0xFFFFFFFF, showLost=False): """Wireshark version must >= 2.0""" wireSharkWindow = automation.WindowControl(searchDepth=1, ClassName='Qt5QWindowIcon') if wireSharkWindow.Exists(0, 0): wireSharkWindow.SetActive() else: automation.Logger.WriteLine('can not find wireshark', automation.ConsoleColor.Yellow) return tree = wireSharkWindow.TreeControl(searchDepth=4, SubName='Packet list') left, top, right, bottom = tree.BoundingRectangle tree.Click(10, 30) automation.SendKeys('{Home}{Ctrl}{Alt}4') time.sleep(0.5) tree.Click(10, 30) headers = [] headerFunctionDict = { 'No': int, 'Time': float, 'Source': str, 'Destination': str, 'Protocol': str, 'Length': int, 'Info': str, } index = 0 payloadStr = 'PT=DynamicRTP-Type-' + str(payload) packets = [] for item, depth in automation.WalkTree( tree, getFirstChildFunc=lambda c: c.GetFirstChildControl(), getNextSiblingFunc=lambda c: c.GetNextSiblingControl()): if isinstance(item, automation.HeaderControl): headers.append(item.Name.rstrip('.')) elif isinstance(item, automation.TreeItemControl): if index == 0: if len(packets) >= maxPackets: break packet = PacketInfo() name = item.Name packet.__dict__[headers[index]] = headerFunctionDict[ headers[index]](name) if headers[index] == 'Info': findPayload = True while findPayload: ptIndex = name.find('PT=DynamicRTP-Type', 1) if ptIndex > 0: info = name[:ptIndex] name = name[ptIndex:] findPayload = True else: info = name findPayload = False packet.Info = info if info.find(payloadStr) >= 0: packet = copy.copy(packet) startIndex = info.find('Seq=') if startIndex > 0: endIndex = info.find(' ', startIndex) packet.Seq = int(info[startIndex + 4:endIndex].rstrip(',')) startIndex = info.find('Time=', startIndex) if startIndex > 0: endIndex = startIndex + 5 + 1 while str.isdigit(info[startIndex + 5:endIndex] ) and endIndex <= len(info): packet.TimeStamp = int(info[startIndex + 5:endIndex]) endIndex += 1 if packet.No >= beginNo: packets.append(packet) automation.Logger.WriteLine( 'No: {0[No]:<10}, Time: {0[Time]:<10}, Protocol: {0[Protocol]:<6}, Length: {0[Length]:<6}, Info: {0[Info]:<10},' .format(packet.__dict__)) index = (index + 1) % len(headers) if item.BoundingRectangle[3] >= bottom: automation.SendKeys('{PageDown}') time.sleep(0.1) AnalyzePackets(packets, sampleRate, showLost)
def KeyEvent(self, keycode): UIAuto.SendKeys(keycode) return True
def KeyEvent(self, keycode): self.JudgeSize() UIAuto.SendKeys(keycode) return True
# 在“文件”菜单的子菜单中找到“保存”,点击 # save = uiautomation.MenuItemControl(Name="保存(S)") # save.Click() # 点击“文件”后,按三次“下”,在按一次“回车”,保存文件 # uiautomation.SendKey(uiautomation.Keys.VK_DOWN) # uiautomation.SendKey(uiautomation.Keys.VK_DOWN) # uiautomation.SendKey(uiautomation.Keys.VK_DOWN) # uiautomation.SendKey(uiautomation.Keys.VK_ENTER) # 利用快捷键保存文件内容,键入S uiautomation.SendKey(uiautomation.Keys.VK_S) # 由于在之前的操作完成后,光标自动进入文件名输入域 # 故,直接在新弹出的文件管理窗口,输入保存的文件路径和文件名 uiautomation.SendKeys(r"C:\Users\aragale\Desktop\demo.txt") # 点击文件管理窗口的“保存”按钮 uiautomation.ButtonControl(Name="保存(S)").Click() time.sleep(1) # 检查文件是否存在 is_file = os.path.exists(r"C:\Users\aragale\Desktop\demo.txt") # 或者 # is_file = os.path.isfile(r"C:\Users\aragale\Desktop\demo.txt") if is_file: # 用os打开文件 # os.system("start /b C:\\Users\\aragale\\Desktop\\demo.txt") # 读取文件内容 # content = uiautomation.EditControl(AutomationId="15").GetValuePattern().Value
def Sendkeys(self, keys): automation.SendKeys(keys)
#!python3 # -*- coding:utf-8 -*- import sys import subprocess import uiautomation as automation if __name__ == '__main__': isTop = 1 print(sys.argv) if len(sys.argv) == 2: isTop = int(sys.argv[1]) note = automation.WindowControl(searchDepth=1, ClassName='Notepad') if note.Exists(0, 0): note.SetTopmost(isTop) else: subprocess.Popen('notepad') note.Refind() note.SetTopmost(isTop) note.Move(0, 0) note.Resize(400, 300) edit = automation.EditControl(searchFromControl=note) edit.Click() automation.SendKeys('I\'m a topmost window!!!')