def SendKeysToAllWindows(self, title_regex): "Sends the keystroke to all windows whose title matches the regex" # We need to call find_windows on our own because Application.connect_ will # call find_window and throw if it finds more than one match. all_matches = pywinauto.findwindows.find_windows(title_re=title_regex) # We need to store all window handles that have been sent keys in order # to avoid reactivating windows and doing unnecesary refreshes. This is a # side effect of having to call Application.connect_ on each regex match. # We need to loop through each open window collection to support edge # cases like Google Canary where the Window title is identical to Chrome. processed_handles = [] for win in all_matches: app = Application() app.connect_(handle=win) open_windows = app.windows_(title_re=title_regex) for openwin in open_windows: if openwin.handle in processed_handles: continue openwin.TypeKeys("{F5}") processed_handles.append(openwin.handle) time.sleep(1)
def SendKeysToAllWindows(self, title_regex): "Sends the keystroke to all windows whose title matches the regex" # We need to call find_windows on our own because Application.connect_ will # call find_window and throw if it finds more than one match. all_matches = pywinauto.findwindows.find_windows(title_re=title_regex) # We need to store all window handles that have been sent keys in order # to avoid reactivating windows and doing unnecesary refreshes. This is a # side effect of having to call Application.connect_ on each regex match. # We need to loop through each open window collection to support edge # cases like Google Canary where the Window title is identical to Chrome. processed_handles = [] for win in all_matches: app = Application() app.connect_(handle=win) open_windows = app.windows_(title_re=title_regex) for openwin in open_windows: if openwin.handle in processed_handles: continue openwin.TypeKeys('{F5}') processed_handles.append(openwin.handle) time.sleep(1)
def safari(self): try: app = Application() app.connect_(path=r"C:\Program Files\Safari\Safari.exe") safari = app.top_window_() safari.TypeKeys("{F5}") except (WindowNotFoundError, ProcessNotFoundError): self.safari64() pass
def safari(self): try: app = Application() app.connect_(path=r'C:\Program Files\Safari\Safari.exe') safari = app.top_window_() safari.TypeKeys('{F5}') except (WindowNotFoundError, ProcessNotFoundError): self.safari64() pass
def ie(self): try: app = Application() app.connect_(title_re='.*Internet Explorer') ie = app.window_(title_re='.*Internet Explorer') ie.TypeKeys('{F5}') if self.is64bit: self.TypeKeys64() except WindowNotFoundError: pass
def testConnect_process(self): "Test that connect_() works with a process" app1 = Application() app1.start_(_notepad_exe()) app_conn = Application() app_conn.connect_(process = app1.process) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def iron(self): try: app = Application() app.connect_(title_re='.*- Iron') iron = app.window_(title_re='.*- Iron') iron.TypeKeys('{F5}') if self.is64bit: self.TypeKeys64() except WindowNotFoundError: pass
def chrome(self): try: app = Application() app.connect_(title_re='.*- Google Chrome') chrome = app.window_(title_re='.*- Google Chrome') chrome.TypeKeys('{F5}') if self.is64bit: self.TypeKeys64() except WindowNotFoundError: pass
def firefox(self): try: app = Application() app.connect_(title_re='.*Mozilla Firefox') firefox = app.window_(title_re='.*Mozilla Firefox') firefox.TypeKeys('{F5}') if self.is64bit: self.TypeKeys64() except WindowNotFoundError: pass
def testConnect_process(self): "Test that connect_() works with a process" app1 = Application() app1.start_(_notepad_exe()) app_conn = Application() app_conn.connect_(process=app1.process) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def opera(self): try: app = Application() app.connect_(title_re='.*Opera') ie = app.window_(title_re='.*Opera') ie.TypeKeys('{F5}') if self.is64bit: self.TypeKeys64() except WindowNotFoundError: pass
def safari64(self): # Safari can be installed under either Program Files directories when # running 64bit Windows. We call this method if the other one errors out. try: app = Application() app.connect_(path=r'C:\Program Files (x86)\Safari\Safari.exe') safari = app.top_window_() safari.TypeKeys('{F5}') except (WindowNotFoundError, ProcessNotFoundError): pass
def safari64(self): # Safari can be installed under either Program Files directories when # running 64bit Windows. We call this method if the other one errors out. try: app = Application() app.connect_(path=r"C:\Program Files (x86)\Safari\Safari.exe") safari = app.top_window_() safari.TypeKeys("{F5}") except (WindowNotFoundError, ProcessNotFoundError): pass
def safari(self): try: app = Application() app.connect_(path=r'C:\Program Files\Safari\Safari.exe') ie = app.top_window_() ie.TypeKeys('{F5}') if self.is64bit: self.TypeKeys64() except (WindowNotFoundError, ProcessNotFoundError): self.safari64() pass
def testConnect_handle(self): "Test that connect_() works with a handle" app1 = Application() app1.start_(_notepad_exe()) handle = app1.UntitledNotepad.handle app_conn = Application() app_conn.connect_(handle = handle) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def testConnect_handle(self): "Test that connect_() works with a handle" app1 = Application() app1.start_(_notepad_exe()) handle = app1.UntitledNotepad.handle app_conn = Application() app_conn.connect_(handle=handle) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def matchXl_dict(self,year): self.book = xlrd.open_workbook(self.from_this_dir('C:\\MYP\\Python\\custom.xlsx'), formatting_info=False) self.sheet = self.book.sheet_by_name('Sheet1') xlval = self.sheet.col_values( 0,0,4) Timings.Defaults() app = Application() try: app.connect_(title_re = ".*Skip Logic.*") except: app.start_('C:\MYP\Swami-KT\MYP_09_00_00_93\QATools\start.bat') time.sleep(5) app.connect_(title_re = ".*Skip Logic.*") Timings.Fast()
def testConnect_windowspec(self): "Test that connect_() works with a windowspec" app1 = Application() app1.start_(_notepad_exe()) #unused var: handle = app1.UntitledNotepad.handle app_conn = Application() try: app_conn.connect_(title = "Untitled - Notepad") except findwindows.WindowAmbiguousError: wins = findwindows.find_windows(title = "Untitled - Notepad") app_conn.connect_(handle = wins[0]) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def testConnect_windowspec(self): "Test that connect_() works with a windowspec" app1 = Application() app1.start_(_notepad_exe()) #unused var: handle = app1.UntitledNotepad.handle app_conn = Application() try: app_conn.connect_(title="Untitled - Notepad") except findwindows.WindowAmbiguousError: wins = findwindows.find_windows(title="Untitled - Notepad") app_conn.connect_(handle=wins[0]) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
class DialogHandler2(object): ''' ''' def __init__(self): self.app = Application() self.dlg = None def control_dialog( self, button_name = '', tries = 3, timeout = 1, **search_args ): ''' ''' if search_args.has_key('class_name') and \ search_args['class_name'] == 'tooltips_class32': _title = 'ToolTips' if search_args.has_key('title'): _title = '%s' % search_args['title'] _button = '%s' % button_name while tries != 0: try: self.dlg = self.app.connect_(**search_args) if button_name: self.dlg[_title][_button].Click() print 'Found dialog "%s". Clicked on its "%s" button.' % (_title, _button) else: self.dlg[_title].Click() print 'Found dialog "%s". Clicked on it directly.' % _title time.sleep(timeout) except (WindowNotFoundError, MatchError): break except ControlNotEnabled: continue except Exception, e: print e.message tries -= 1
def testConnect_path(self): "Test that connect_() works with a path" app1 = Application() app1.start_(_notepad_exe()) app_conn = Application() app_conn.connect_(path=self.notepad_subpath) self.assertEqual(app1.process, app_conn.process) app_conn = Application() if is_x64_Python() or not is_x64_OS(): app_conn.connect_(path=r"c:\windows\system32\notepad.exe") else: app_conn.connect_(path=r"c:\windows\syswow64\notepad.exe") self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def testConnect_path(self): "Test that connect_() works with a path" app1 = Application() app1.start_(_notepad_exe()) app_conn = Application() app_conn.connect_(path = self.notepad_subpath) self.assertEqual(app1.process, app_conn.process) app_conn = Application() if is_x64_Python() or not is_x64_OS(): app_conn.connect_(path = r"c:\windows\system32\notepad.exe") else: app_conn.connect_(path = r"c:\windows\syswow64\notepad.exe") self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def RunTestTool(self, year, quarter, sleeptime): Timings.Defaults() app = Application() try: app.connect_(title_re = ".*a.*") sys.stderr.write ( 'connected to window '+'\n') except: import sys, string, os app.start_('C:\\MYP\\Python\\start.bat') time.sleep(5) app.connect_(title_re = ".*a.*") sys.stderr.write ( 'connected to window '+'\n') app.connect_(title_re = ".*a.*") app.top_window_().Restore() Timings.Fast() window = app.window_(process=18000) window.SetFocus() time.sleep(5) app.top_window_().Click() time.sleep(5) #window.TypeKeys("{TAB 2}") window.TypeKeys("{RIGHT 2}") window.TypeKeys("{TAB 4}") sys.stderr.write ( 'tabbing completed'+'\n') dict = app.top_window_()._ctrl_identifiers() print dict for k,v in dict.items(): #print v for v1 in v: if (v1==u'a'): print k.handle #k.Click() app.top_window_().YearComboxBox.Select(year) #app.top_window_().ComboBox7.Select("a") app.top_window_()['a'].Click() sys.stderr.write ( 'Setting Options and Clicked'+'\n') print app.top_window_().PopulationComboBox1.ItemTexts() measures= [] measures = app.top_window_().PopulationComboBox1.ItemTexts() print measures mmap= { 'a':['b'], } #from collections import OrderedDict #mmap1={} #mmap1=OrderedDict((mmap[key], True) for key in mmap) measures=mmap.keys() measures.sort() s='' s1='' dictErrors ={} i=0 previousError='' previousSkip='' for measure in measures: i=i+1 #if(i==6): #break print 'using ' print measure indicators=[] indicators=mmap[measure] if not measure == '': # Change the not operator if you want to run it for all cases in one go. app.top_window_().PopulationComboBox1.Select(measure) #indicators= app.top_window_().IndicatorComboBox3.ItemTexts() for indicator in indicators: if indicator == '': continue app.top_window_().IndicatorComboBox3.Select(indicator) app.top_window_()['Create and Run TestsButton'].Click() #app.top_window_()['Create and Run TestsButton'].Click() #time.sleep(12) while(True): time.sleep(1) times_Run = app.top_window_()['Testing:Edit'].Texts()[0].strip(" ").split()[0] if(times_Run=='00100'): s1=app.top_window_()['Skip Logic ErrorsEdit2'].Texts()[0].strip(" ") s = app.top_window_()['Measure Engine ErrorsEdit2'].Texts()[0].strip(" ") print s print s1 break #print dictErrors sleeptime = 30 errors='' time.sleep(sleeptime) sys.stderr.write ( 'Slept for '+str(sleeptime)+'\n') #print s+s1 #s1 = app.top_window_()['Skip Logic ErrorsEdit2'].Texts()[0] #s = app.top_window_()['Measure Engine ErrorsEdit2'].Texts()[0] print errors print dictErrors if(errors != '' ): raise AssertionError(errors) app.start_('C:\\MYP\\Python\\stop.bat') print 'reached3' #MayNotWork app.kill() app.start_('C:\\MYP\\Python\\stop.bat') sys.stderr.write ( 'All done')
class banques: """Classe principale permettant de regrouper les fonctions d'automatisation""" def __init__(self): "Constructeur de l'objet principale du module pywinauto: l'applicaton a automatiser" self.app = Application() #Etape 0 (cf blog www.python4d.com) try: #Connection de l'objet app avec le process lié à la fenêtre principale Google Chrome self.app.connect_(title_re=".* - Google Chrome", class_name=r"Chrome_WidgetWin_1") except: #lancer un nouveau process Chrome et s'y connecter #Etape 1(cf blog www.python4d.com) self.app.start_(r"C:\Users\damien\AppData\Local\Google\Chrome\Application\chrome.exe", timeout=2) sleep(5) self.app["Chrome_WidgetWin_1"].Maximize() #Mettre le curseur souris à un endroit qui ne perturbe pas le focus des fenêtres du browser SetCursorPos(0, 0) sleep(1) #fenêtre de l'application tout entière Chrome self.ChromeWin = self.app["Chrome_WidgetWin_1"] #fenêtre (textbox) de l'URL self.ChromeUrl = self.app["Chrome_WidgetWin_1"]["Chrome_OmniboxView"] #Etape n°2 (cf blog www.python4d.com) self.newtab() def newtab(self): "Méthode qui lance un CTRL-T sur l'application Chrome: création d'un nouvel onglet" sleep(2) self.ChromeWin.TypeKeys(r"^T") #Mettre le curseur souris à un endroit qui ne perturbe pas le focus des fenêtres du browser SetCursorPos(0, 0) sleep(1) def matchtemplate(self, img1, img2): "Méthode de comparaison entre deux images [cv2.matchTemplate (OpenCV)]" imgVignette=cv2.imread(img2) imgEcran=cv2.imread(img1) result=cv2.matchTemplate(imgEcran,imgVignette,5) (_, _, _, maxLoc) = cv2.minMaxLoc(result, mask=None) return maxLoc def ingdirect(self, compte="12345{TAB}01011901{ENTER}", mdp="012345"): "Methode automatisant les entrées claviers et souris pour le site INGDIRECT" dirbase = r".//ingdirect//" adrbanque = r"https://secure.ingdirect.fr/public/displayLogin.jsf" #Etape n°3 (cf blog www.python4d.com) self.ChromeUrl.TypeKeys("^a" + adrbanque + "{ENTER}"),sleep(4) #Etape n°4 (cf blog www.python4d.com) self.ChromeWin.TypeKeys(compte),sleep(5) #Etape n°5 (cf blog www.python4d.com) WinBoursoramaImage = self.ChromeWin.CaptureAsImage() WinBoursoramaImage.save(dirbase + "WebImage.png") coordy = [0,]*10 coordx = [0,]*10 x, y = self.matchtemplate(dirbase + "WebImage.png", dirbase + "VALIDER.png") #Etape n°6/9 (cf blog www.python4d.com) for i in range(0, 10): small = str(i) + '.png' coordx[i], coordy[i] = self.matchtemplate(dirbase + "WebImage.png", dirbase + small) premiere_absisse = x #absisse du premier code correspond à l'absisse de la forme "VALIDER". #Etape n°7/9 (cf blog www.python4d.com) for i in range(3): codex, codey = self.matchtemplate(dirbase + "WebImage.png", dirbase + "code.png") code=int(round(abs(premiere_absisse-codex)/32.0)) #on considère que chaque emplacement de code est séparé par 32 points (! dépend de la résolution !) self.ChromeWin.ClickInput(coords=(coordx[int(mdp[code])] + 10, coordy[int(mdp[code])] + 10), double=False) WinBoursoramaImage = self.ChromeWin.CaptureAsImage() WinBoursoramaImage.save(dirbase + "WebImage.png") #Etape n°8 (cf blog www.python4d.com) self.ChromeWin.ClickInput(coords=(x + 10, y + 10), double=False)
class banques: """Classe principale permettant de regrouper les fonctions d'automatisation""" def __init__(self): "Constructeur de l'objet principale du module pywinauto: l'applicaton a automatiser" self.app = Application() #Etape 0 (cf blog www.python4d.com) try: #Connection de l'objet app avec le process lié à la fenêtre principale Google Chrome self.app.connect_(title_re=".* - Google Chrome", class_name=r"Chrome_WidgetWin_1") except: #lancer un nouveau process Chrome et s'y connecter #Etape 1(cf blog www.python4d.com) self.app.start_( r"C:\Users\damien\AppData\Local\Google\Chrome\Application\chrome.exe", timeout=2) sleep(5) self.app["Chrome_WidgetWin_1"].Maximize() #Mettre le curseur souris à un endroit qui ne perturbe pas le focus des fenêtres du browser SetCursorPos(0, 0) sleep(1) #fenêtre de l'application tout entière Chrome self.ChromeWin = self.app["Chrome_WidgetWin_1"] #fenêtre (textbox) de l'URL self.ChromeUrl = self.app["Chrome_WidgetWin_1"]["Chrome_OmniboxView"] #Etape n°2 (cf blog www.python4d.com) self.newtab() def newtab(self): "Méthode qui lance un CTRL-T sur l'application Chrome: création d'un nouvel onglet" sleep(2) self.ChromeWin.TypeKeys(r"^T") #Mettre le curseur souris à un endroit qui ne perturbe pas le focus des fenêtres du browser SetCursorPos(0, 0) sleep(1) def matchtemplate(self, img1, img2): "Méthode de comparaison entre deux images [cv2.matchTemplate (OpenCV)]" imgVignette = cv2.imread(img2) imgEcran = cv2.imread(img1) result = cv2.matchTemplate(imgEcran, imgVignette, 5) (_, _, _, maxLoc) = cv2.minMaxLoc(result, mask=None) return maxLoc def ingdirect(self, compte="12345{TAB}01011901{ENTER}", mdp="012345"): "Methode automatisant les entrées claviers et souris pour le site INGDIRECT" dirbase = r".//ingdirect//" adrbanque = r"https://secure.ingdirect.fr/public/displayLogin.jsf" #Etape n°3 (cf blog www.python4d.com) self.ChromeUrl.TypeKeys("^a" + adrbanque + "{ENTER}"), sleep(4) #Etape n°4 (cf blog www.python4d.com) self.ChromeWin.TypeKeys(compte), sleep(5) #Etape n°5 (cf blog www.python4d.com) WinBoursoramaImage = self.ChromeWin.CaptureAsImage() WinBoursoramaImage.save(dirbase + "WebImage.png") coordy = [ 0, ] * 10 coordx = [ 0, ] * 10 x, y = self.matchtemplate(dirbase + "WebImage.png", dirbase + "VALIDER.png") #Etape n°6/9 (cf blog www.python4d.com) for i in range(0, 10): small = str(i) + '.png' coordx[i], coordy[i] = self.matchtemplate(dirbase + "WebImage.png", dirbase + small) premiere_absisse = x #absisse du premier code correspond à l'absisse de la forme "VALIDER". #Etape n°7/9 (cf blog www.python4d.com) for i in range(3): codex, codey = self.matchtemplate(dirbase + "WebImage.png", dirbase + "code.png") code = int( round(abs(premiere_absisse - codex) / 32.0) ) #on considère que chaque emplacement de code est séparé par 32 points (! dépend de la résolution !) self.ChromeWin.ClickInput(coords=(coordx[int(mdp[code])] + 10, coordy[int(mdp[code])] + 10), double=False) WinBoursoramaImage = self.ChromeWin.CaptureAsImage() WinBoursoramaImage.save(dirbase + "WebImage.png") #Etape n°8 (cf blog www.python4d.com) self.ChromeWin.ClickInput(coords=(x + 10, y + 10), double=False)
def clickSpot(x,y): app = Application() comapp = app.connect_(path = "explorer") for i in comapp.windows_(): if "Progman" == i.FriendlyClassName(): i.ClickInput(coords=(x,y))