def show(): from __future__ import print_function from pywinauto import Application # Open "Control Panel" Application().start('control.exe') app = Application(backend='uia').connect(path='explorer.exe', title='Control Panel') # Go to "Programs" app.window(title='Control Panel').ProgramsHyperlink.invoke() app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0) # Go to "Installed Updates" app.window(title='Programs').child_window( title='View installed updates', control_type='Hyperlink').invoke() app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0) list_box = app.InstalledUpdates.FolderViewListBox # list all updates items = list_box.descendants(control_type='ListItem') all_updates = [item.window_text() for item in items] print('\nAll updates ({}):\n'.format(len(all_updates))) print(all_updates) # list updates from "Microsoft Windows" group only windows_group_box = list_box.child_window(title_re='^Microsoft Windows.*', control_type='Group') windows_items = windows_group_box.descendants(control_type='ListItem') windows_updates = [item.window_text() for item in windows_items] print('\nWindows updates only ({}):\n'.format(len(windows_updates))) print(windows_updates)
def wizard_setup(): Application(backend="uia").start(path + "client.exe") time.sleep(15) app = Application(backend="uia").connect( title=" Мастер первоначальной настройки") dlg1 = app.window(title=" Мастер первоначальной настройки") dlg1.Далее.click() time.sleep(1) dlg1.Далее.click() time.sleep(1) dlg1.Подтвердитьпароль.click() time.sleep(1) dlg1.Далее.click() time.sleep(1) dlg1.Далее.click() time.sleep(1) dlg1.Далее.click() time.sleep(1) dlg1.Далее.click() time.sleep(1) dlg1.Завершить.click() time.sleep(5) app1 = Application(backend="uia").connect( title=" Мастер первоначальной настройки") dlg2 = app1.window(title=" Мастер первоначальной настройки") time.sleep(1) dlg2.OK.click() #попытки создать iidk через интерфейс, не получается выбрать конректно объект iidk для создания """
class Application: def __init__(self, target): self.application = WinApplication(backend="win32").start(target) self.main_window = self.application.window(title="Free Address Book") self.main_window.wait("visible") self.groups = GH(self) def destroy(self): self.application.window(title="Free Address Book").close()
def run_storm(self): app, Wnd_Main = None, None try: app = Application().connect(title_re="StormInterface") Wnd_Main = app.window(title_re="StormInterface") Wnd_Main.wait('ready') except: app = Application().start(self.stormpath) Wnd_Main = app.window(title_re="StormInterface") Wnd_Main.wait('ready') finally: return app, Wnd_Main
def run_storm(self): app, Wnd_Main = None, None try: app = Application().connect(title_re="StormInterface") Wnd_Main = app.window(title_re="StormInterface") Wnd_Main.wait('ready') except: config = Config(self.parent) app = Application().start(config.getConfAttr('settings', 'stormpath')) Wnd_Main = app.window(title_re="StormInterface") Wnd_Main.wait('ready') finally: return app, Wnd_Main
def init_weixin(): app = Application().start( r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe") if not app.windows(): app = Application().connect( path=r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe") dlg = app.window(title=u"微信", class_name="WeChatMainWndForPC") dlg.move_window(0, 0) ie_dlg = app.window(title=u"微信", class_name="CefWebViewWnd") ie_dlg.move_window(0, 0) ie_dlg.set_focus() dlg.set_focus() print(ie_dlg.print_control_identifiers()) return dlg
def auto_login(steamid, name, lock): eel.info("使用快取登入", "使用者名稱:" + name + "\nsteamid:" + steamid, "console") key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\Valve\Steam", 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, "AutoLoginUser", 0, winreg.REG_SZ, name) winreg.SetValueEx(key, "RememberPassword", 0, winreg.REG_DWORD, 0x00000001) exe, t = winreg.QueryValueEx(key, "SteamExe") winreg.CloseKey(key) si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW eel.info("關閉Steam", "", "console") close_steam(exe, si) eel.info("啟動steam", "", "console") app = APP().start(exe) login_gui = app.window(title_re='Steam [^Guard].*', class_name='vguiPopupWindow') eel.info("等待 '主頁面'", "", "console") wait_time = app_setting("wait_steam_start") eel.info("容許等待時間" + wait_time, "", "console") eel.sleep(int(wait_time)) try: login_gui.wait_not("ready", wait_time) #等待介面 except: eel.info("注意!", "無法使用快取登入\n將使用模擬登入", "console") login(steamid, lock, app, True) else: del app lock.release() eel.info("登入成功", "", "console")
class Converter: def __init__(self): self.exe = "C://Program Files (x86)/Auntec/嗨格式PDF转换器/HiPdfConvert.exe" self.app = Application(backend="uia") # self.app.start(self.exe) self.app.connect(path=self.exe) # time.sleep(8) def windows(self): s1 = self.app.window(best_match='嗨格式PDF转换器1.0') s2 = s1["pdf转文件"] s2.print_control_identifiers() s3 = s2.child_window(title="文件名称", control_type="Text") s3.type_keys("afda") s4 = s2.child_window(title="开始转换", control_type="Text") s4.type_keys("{ENTER}") def open(self): auto.hotkey("alt", "tab") # auto.moveTo(x=980, y=990) # auto.click() auto.moveTo(x=580, y=251) auto.click() f = "D://mygit/cpa_std/cpa_std/vehicle_insurance/data/pdf/eacd2c918f264f568096f4cea0e698f0.pdf" f = os.path.abspath(f) auto.typewrite(message=f) auto.press("enter") auto.moveTo(x=1400, y=911) auto.click() auto.moveTo(x=700, y=611) auto.click()
def init_sv_login(event, sv_app, menu_names): """ function to get the label that is clicked and launch the sv application """ # Launch the application evt_id = event.GetId() - 1 app = Application(backend='uia').start(sv_app) # get the Dialogue Handler dlg = app.window(title_re='Singleview Convergent Billing.*') db_pane = dlg.child_window(title="Database", control_type="Pane") # set variables from the clicked menu keys_list = list(menu_names.keys()) db = menu_names[keys_list[evt_id]][0] uname = menu_names[keys_list[evt_id]][1] passwd = menu_names[keys_list[evt_id]][2] # set database name db_edit = db_pane.Edit0 db_edit.set_text(db) # set user name uname_edit = db_pane.Edit3 uname_edit.set_text(uname) # set password name pass_edit = db_pane.Edit2 pass_edit.set_text(passwd) dlg.Ok.click()
def init_weixin(): # app = Application().connect( # path=r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe") # # if not app.windows(): # app = Application().connect( # path=r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe") # # # # dlg = app.window(title=u"微信", class_name="WeChatMainWndForPC") # dlg.move_window(0, 0) # dlg.maximize() # dlg.set_focus() dlgs = [] rets = pywinauto.findwindows.find_windows(class_name="WeChatMainWndForPC") for ret in rets: app = Application().connect(handle=ret) dlg = app.window(title=u"微信", class_name="WeChatMainWndForPC") dlg.move_window(0, 0) dlg.maximize() dlg.set_focus() dlgs.append(dlg) time.sleep(1) return dlgs
def install_securos(name): app = Application(backend="uia").start(r"C:/builds/" + name).connect( title='SecurOS Enterprise - InstallShield Wizard') dlg = app.window(title='SecurOS Enterprise - InstallShield Wizard') time.sleep(2) #раньше работало так как закомментированно ниже, потом почемуто начало работать через раз #dlg.wait('exists') #dlg.print_control_identifiers() #dlg.child_window(best_match='ComboBox', auto_id="306").select("Русский") #dlg.window(best_match='ComboBox', auto_id="306").select("Русский") dlg.OK.click() #неудачные попытки обойти sleep и смену окон #app.WindowSpecification.Далее.wait('enabled').click() #OpenDialog = pwa_app.window(best_match=u'Open', class_name='#32770').wait('visible', timeout=20, retry_interval=0.5) #app.wait_for_process_exit(timeout=150) #dlg.wait('visible', timeout=150) #window = pywinauto.timings.WaitUntilPasses(20, 0.5, lambda: app.window_(title=Win)) #dlg.Далее.wait('visible', timeout=150) time.sleep(150) app1 = Application(backend="uia").connect( title='SecurOS Enterprise - InstallShield Wizard') dlg1 = app1.window(title='SecurOS Enterprise - InstallShield Wizard') time.sleep(5) dlg1.Далее.click() time.sleep(5) dlg1.Япринимаюусловиялицензионногосоглашения.click() time.sleep(2) dlg1.Далее.click() time.sleep(2) dlg1.Далее.click() time.sleep(2) dlg1.Далее.click() time.sleep(2) dlg1.Далее.click() time.sleep(2) dlg1.Далее.click() time.sleep(2) dlg1.Далее.click() time.sleep(2) dlg1.Установить.click() #dlg1.Готово.wait('visible', timeout=550) time.sleep(640) dlg1.Готово.click()
def tm_init(): if (os.path.exists(r"E:\TCMS_LIVE\Client Suite")): templa_file = r"E:\TCMS_LIVE\Client Suite\TemplaCMS32.exe" app = Application(backend='uia').connect(path=templa_file) templa = app.window(title_re='TemplaCMS*') return [templa, app] else: return None
def run_creon_plus(username: str, password: str, certification_password: str, starter_path: str): app = Application().start('%s /prj:cp' % starter_path) sleep(1) typewrite('\n', interval=0.1) dialog = timings.WaitUntilPasses( 30, 1, lambda: app.window(handle=find_window(title='CREON Starter')) ) username_input = getattr(dialog, '1') username_input.Click() username_input.TypeKeys(username) password_input = getattr(dialog, '2') password_input.Click() password_input.TypeKeys(password) certification_password_input = getattr(dialog, '3') certification_password_input.Click() certification_password_input.TypeKeys(certification_password) press('enter')
def wizard_load_from_json(): time.sleep(1) Application(backend="uia").start(path + "client.exe") time.sleep(15) app = Application(backend="uia").connect( title=" Мастер первоначальной настройки") dlg = app.window(title=" Мастер первоначальной настройки") dlg.Импортироватькофигурационныйфайл.click() dlg.Далее.click() time.sleep(2) dlg['Путь к файлу:Edit'].set_text( 'C:\\ProgramData\\ISS\\Sys_config\\new_system_with_iidk.json') time.sleep(2) dlg.Далее.click() time.sleep(1) dlg.Восстановить.click() time.sleep(1) dlg.Завершить.click()
def msPaintDemo(self): parser = argparse.ArgumentParser() parser.add_argument("--log", help="enable logging", type=str, required=False) args = parser.parse_args() actionlogger.enable() logger = logging.getLogger('pywinauto') if args.log: logger.handlers[0] = logging.FileHandler(args.log) app = Application(backend='uia').start(r'mspaint.exe') dlg = app.window(title_re='.* - Paint') # File->Open menu selection dlg.File_tab.click() dlg.child_window(title='Open', control_type='MenuItem', found_index=0).invoke() # handle Open dialog file_name_edit = dlg.Open.child_window(title="File name:", control_type="Edit") file_name_edit.set_text('image.jpg') dlg.Open.child_window(title="Open", auto_id="1", control_type="Button").click() dlg.ResizeButton.click() dlg.ResizeAndSkew.Pixels.select() if dlg.ResizeAndSkew.Maintain_aspect_ratio.get_toggle_state() != 1: dlg.ResizeAndSkew.Maintain_aspect_ratio.toggle() dlg.ResizeAndSkew.HorizontalEdit1.set_text('100') dlg.ResizeAndSkew.OK.click() # Select menu "File->Save as->PNG picture" dlg.File_tab.click() dlg.SaveAsGroup.child_window(title="Save as", found_index=1).invoke() dlg.child_window(title='PNG picture', found_index=0).invoke() # Type output file name and save dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png') dlg.SaveAs.Save.click() if dlg.ConfirmSaveAs.exists(): dlg.ConfirmSaveAs.Yes.click() # Close application dlg.close()
class FimeIntegriHelper(XObject): def __init__(self): super(FimeIntegriHelper, self).__init__() self._fime_app = None self._fime_app_mainwin = None def sync(self): try: if self._fime_app is None: self._fime_app = Application(backend='uia').connect(title_re='EVA*') self._fime_app_mainwin = self._fime_app.window(title_re='EVAL*') self._fime_app_mainwin.print_control_identifiers(depth=3, filename='_fime_app_mainwin.txt') except Exception as e: self.exception(e) return False return True def _click(self, ui_object): local = ui_object.element_info.rectangle ui_object.set_focus() pywinauto.mouse.click(coords=(local.left + 5, local.top + 5)) def handle_pop_message(self): try: dlg_pop_message = self._fime_app_mainwin.window(title='POP Message', class_name='ThunderRT6UserControlDC') dlg_pop_message.wait('ready', timeout=20) self.info('dlg_pop_message 1') PassButton = self._fime_app_mainwin.window(title='Pass', control_type="Button", class_name='ThunderRT6CommandButton') self._click(PassButton.wrapper_object()) except Exception as e: self.exception(e) self.info('Can not find window(POP Message)') else: try: PassButton = dlg_pop_message.window(title='Pass', control_type="Button") self._click(PassButton.wrapper_object()) except Exception as e: self.exception(e) self.info('Can not click Pass Button')
def ipo(self): pyperclip.copy("") app = Application().connect(handle=self.main) app["股票交易系统"].window(handle=self.tree_handle).select("\\新股申购\\新股批量申购") print_time(self.tree_handle) time.sleep(9) app.top_window()["确定"].click() print_time(" width:%d,height:%d", self.screen_width, self.screen_height) self.ipo_grid_handle = op.WindowFromPoint( POINT(int(self.screen_width / 2), int(self.screen_height / 2))) print_time(ctypes.WinError()) print_time( op.SendMessageW(self.ipo_grid_handle, WM_COMMAND, 57634, self.ipo_grid_path[-1])) print_time("ipo grid handle:%d" % self.ipo_grid_handle) can_ipo = pyperclip.paste() print_time(ctypes.WinError()) print_time(can_ipo) dict_ipo = util.BaseTypeUtil.analyze_position(can_ipo) pos = [] for (j, k) in zip(dict_ipo.values(), range(1, 10, 1)): if float(dict(j).get("可申购数量")) > 0.99: pos.append(k) if len(pos) < 1: return rect = app.window(handle=self.ipo_grid_handle).rectangle() height = 16 x = rect.left + 10 first = rect.top + 20 + height / 2 print_time(pos) for i in pos: y = first + (i - 1) * height print_time("x:%d,y:%d,i:%d" % (x, y, i)) mouse_move_click(int(x), int(y)) app["股票交易系统"]["申购Button"].click() time.sleep(9) app.top_window()["是Button"].click()
def html_downloader(list_web , abspath , data_storage): """ download the html file of the website """ ### start the shortcut os.startfile(f'{short_cutpath}\{list_web}') time.sleep(20) ### identify the short cut app = Application(backend = 'uia').connect(title_re = '.*Market Share Stats') send_keys('^s') time.sleep(10) ### check existing check_delete = delete_exist(data_storage , list_web) ### type the name of the path win = app.window(title_re = '.*Market Share Stats') ### go to another path first win.type_keys(short_cutpath,set_foreground=False) send_keys('~') ### go to target path win.type_keys(data_storage,set_foreground=False) send_keys('~') ### delete int and reduce space list_web = list_web.replace('.lnk','') list_web = list_web.replace(' ','') win.type_keys(list_web+'.html',set_foreground=False) send_keys('~') ### send yes time.sleep(5) send_keys('~') ### close the tab send_keys('^{F4}')
def init_sv_login(self, event): """ function to get the label that is clicked and launch the sv application """ # Launch the application evt_id = event.GetId() - 1 try: app = Application(backend='uia').start(self.sv_app) except application.AppStartError as err: show_msg_box("Singview Application Start Failure : {}".format(err)) # get the Dialogue Handler dlg = app.window(title_re='Singleview Convergent Billing.*') db_pane = dlg.child_window(title="Database", control_type="Pane") # set variables from the clicked menu keys_list = list(self.menu_names.keys()) db = self.menu_names[keys_list[evt_id]][0] uname = self.menu_names[keys_list[evt_id]][1] passwd = self.menu_names[keys_list[evt_id]][2] # set database name db_edit = db_pane.Edit0 db_edit.set_text(db) # set user name uname_edit = db_pane.Edit3 uname_edit.set_text(uname) # set password name pass_edit = db_pane.Edit2 pass_edit.set_text(passwd) dlg.Ok.click()
import time from pywinauto import Application cpuz = Application(backend='uia').start('C:\Program Files\CPUID\CPU-Z\cpuz.exe') cpuz_window = cpuz.window() date = cpuz_window.child_window(class_name="Static") window_textbox = cpuz_window.child_window(title="Validate", control_type='Button').click_input()
import logging from pywinauto import actionlogger from pywinauto import Application import argparse parser = argparse.ArgumentParser() parser.add_argument("--log", help="enable logging", type=str, required=False) args = parser.parse_args() actionlogger.enable() logger = logging.getLogger('pywinauto') if args.log: logger.handlers[0] = logging.FileHandler(args.log) app = Application(backend='uia').start(r'mspaint.exe') dlg = app.window(title_re='.* - Paint') # File->Open menu selection dlg.File_tab.click() dlg.child_window(title='Open', control_type='MenuItem', found_index=0).invoke() # handle Open dialog file_name_edit = dlg.Open.child_window(title="File name:", control_type="Edit") file_name_edit.set_text('walter_cat.jpg') # There are 2 Open buttons: # dlg.Open.Open.click() will call drop down list of the file name combo box. # The child_window statement is just copied from print_control_identifiers(). dlg.Open.child_window(title="Open", auto_id="1", control_type="Button").click() dlg.ResizeButton.click() dlg.ResizeAndSkew.Pixels.select()
def data_loading(app, file_path_variable): # from pywinauto.controls.win32_controls import ComboBoxWrapper # from pywinauto.controls.uia_controls import ToolbarWrapper time.sleep(30) # click on the loading button app.window(best_match='National Roads Condition Database - Version*', top_level_only=True)\ .child_window(best_match='Loading').click() # if the file_path_variable directory contains a file 'BatchList' use the 'Select Batch File' # else use 'Create Batch file' if os.path.isfile(file_path_variable + '/BatchList.txt'): filename = file_path_variable + '/BatchList.txt' print("\nfile name exists using Select", filename) time.sleep(30) app.window(best_match='National Roads Condition Database - Version', top_level_only=True) \ .child_window(best_match='Select Batch file').click() filename = filename.replace('/', '\\') print("\nfile exists", filename) time.sleep(15) # check existence of the app2 variable if it is there destroy it as connecting to the file selection # is going to create it and it could get messy if it's still there from processing the previous LA. try: app2 except NameError: print('app2 not used') else: del app2 # Connect to the selection window and enter the batch file name. app2 = Application(backend="uia").connect( title_re='Select a batch file', visible_only=True) print("\nConnect app2 filename is ", filename) app2.window(title_re='Select a batch file') \ .File_name_Edit.set_text(filename) time.sleep(15) batch_split_button2 = app2.window(title_re='Select a batch file') \ .child_window(auto_id='1', control_type="SplitButton") from pywinauto.controls.win32_controls import ButtonWrapper ButtonWrapper(batch_split_button2).click() del app2 else: # else pick the first .hmd file and use 'Create Batch File' print("\nBatchfile file missing") time.sleep(30) # app.window(best_match='National Roads Condition Database - Version', top_level_only=True).child_window( # best_match='OK').click() app.window(best_match='National Roads Condition Database - Version', top_level_only=True) \ .child_window(best_match='Create Batch file').click() # filename = filename.replace('/', '\\') # print("\nfile exists", filename) # time.sleep(15) # app2 = Application(backend="uia").connect(title_re='Select a batch file', visible_only=True) # print("\nConnect app2 filename is ", filename) file_search_variable = (file_path_variable + '/*.hmd').replace( '/', '\\') print("\nfile_search_variable = ", file_search_variable) filename = glob.glob(file_search_variable) # filename = filename[0] print("\nFile found : ", filename) filename = filename[1].replace('/', '\\') time.sleep(20) # click on 'Create Batch File' then OK on the following window # app.window(best_match='National Roads Condition Database') \ # .child_window(best_match='Create Batch file').click() time.sleep(30) app.window(best_match='National Roads Condition Database') \ .child_window(title='NRCD').OK.click() # app.window(best_match='National Roads Condition Database Version *') \ # .child_window(best_match='OK').click() time.sleep(30) # There will be a file selection window. Connect to it (it's not part of NRCD) # So it's a new application. # # But first if app3 is already there get rid of it first. try: app3 except NameError: print('app3 not used') else: del app3 app3 = Application(backend="uia").connect( title='Create a file in the required directory') print("\nconnect app3") time.sleep(15) # edit_text_box2 = app3.window(title_re='Select a batch file') \ # .child_window(best_match="File name:") # from pywinauto.controls.win32_controls import EditWrapper # EditWrapper(edit_text_box2).set_text(filename) # app.window(best_match='National Roads Condition Database - Version *') \ # .child_window(best_match='NRCD') \ # .child_window(best_match='OK').click() # put the filename that was found into the filename box # app3.window(title_re='Create a file in the required directory').print_control_identifiers() app3.window(title_re='Create a file in the required directory') \ .File_name_Edit.set_text(filename) # Click on the open button, this is a bit more involved so that it works with a locked screen. batch_split_button1 = app3.window(title_re='Create a file in the required directory') \ .child_window(auto_id='1', control_type="SplitButton") from pywinauto.controls.win32_controls import ButtonWrapper ButtonWrapper(batch_split_button1).click() # remove references to the window where the filename was entered as it will use # the same variable next time round (next LA) del app3 # if the file_path_variable directory string contains WDM if "WDM" in file_path_variable: # then Survey Contractor = WDM survey_contractor: str = "WDM" # else if the directory string contains 'G-L' select survey contractor 'Ginger-Lehmann' elif "G-L" in file_path_variable: survey_contractor: str = "Ginger-Lehmann" # else if the directory string contains 'PTS' select survey contractor 'Ginger-Lehmann' elif "PTS" in file_path_variable: survey_contractor: str = "PTS" # it's not one of those we know about. Should another contractor start surveying then add another 'elif' else: survey_contractor = "Unknown contractor" print(survey_contractor) from pywinauto.controls.win32_controls import ComboBoxWrapper surveyor_combobox = app.window(best_match='National Roads Condition Database') \ .child_window(best_match='Survey Contractor', control_type='Group') \ .child_window(auto_id="3", control_type="ComboBox") ComboBoxWrapper(surveyor_combobox).select(survey_contractor) # click 'OK' to close the data loading window as we have all the appropriate details entered in the window. app.window(best_match='National Roads Condition Database') \ .child_window(best_match='OK').click() # back on the NRCD main screen, click the process radio button then the actual 'Process' button app.window(best_match='National Roads Condition Database - Version *', top_level_only=True).child_window(best_match='Process').click() # The log entry contains the first file to be loaded (the rest will not appear and NRCD uses the # batchfile to find them logger.info('Starting loading with ' + filename) time.sleep(60) # wait for the loading to finish. It checks the number of windows open for NECD.exe. If these are less than # two the section is complete, otherwise it loops. while nrcd_running_check('2'): logger.info('waiting for loading to complete') time.sleep(300) logger.info('loading completed') return # back to main
def scanner_qa(app, file_path_variable): from pywinauto.controls.win32_controls import ComboBoxWrapper from pywinauto.controls.win32_controls import ButtonWrapper import re # there is a regex search below ! time.sleep(150) main_screen = app.window( best_match='National Roads Condition Database - V*') # turn all the process check boxes off. main_screen_process_checkbox = main_screen.child_window( title="Process", auto_id="15", control_type="CheckBox") main_screen_process_checkbox2 = main_screen.child_window( title="Process", auto_id="16", control_type="CheckBox") main_screen_process_checkbox3 = main_screen.child_window( title="Process", auto_id="17", control_type="CheckBox") main_screen_process_checkbox4 = main_screen.child_window( title="Process", auto_id="18", control_type="CheckBox") time.sleep(60) ButtonWrapper(main_screen_process_checkbox).uncheck_by_click() ButtonWrapper(main_screen_process_checkbox2).uncheck_by_click() ButtonWrapper(main_screen_process_checkbox3).uncheck_by_click() ButtonWrapper(main_screen_process_checkbox4).uncheck_by_click() filename = file_path_variable.replace('/', '\\') print(filename) # time.sleep(15) # use the location of the file_path_variable to extract the local authority, nation and year. local_authority = filename.split("\\")[-1] nation = filename.split("\\")[-2] year: str = re.search('[1-2][0-9]{3}', filename).group(0) # regex search # logger.info('starting Scanner QA output for ' + local_authority) # print(local_authority) print(nation) print(year) logger.info('starting SCANNER QA for ' + local_authority) # Load the human name to database name csv table lookup_table_filename = '//trllimited/data/INF_ScannerQA/Audit_Reports/Tools/LA_to_NRCD_Name.csv' la_lookup_table = pd.read_csv(lookup_table_filename, index_col='Audit_Report_name', dtype={'INDEX': str}) la_db_name: str = la_lookup_table.loc[local_authority, "NRCD_Name"] # enter the Scanner QA section of NRCD and wait for the Survey QA options group to exist. app.window( best_match='National Roads Condition Database', top_level_only=True).child_window(best_match='Scanner QA').click() time.sleep(30) app.window(best_match='National Roads Condition Database - Version *') \ .child_window(title="Survey QA Options", auto_id="9", control_type="Group") \ .wait("exists ready", timeout=90, retry_interval=60) group_control = app.window(best_match='National Roads Condition Database - Version *') \ .child_window(title="Survey QA Options", auto_id="9", control_type="Group") # group_control.print_control_identifiers() # exclude the previous year and the U roads (uncheck_by_click) then select the LA abd survey year. ButtonWrapper( group_control.child_window( title="Include Previous Year", control_type="CheckBox")).uncheck_by_click() ButtonWrapper( group_control.child_window( title="U Roads", control_type="CheckBox")).uncheck_by_click() ComboBoxWrapper( group_control.child_window(auto_id="24", control_type="ComboBox")).select(la_db_name) ComboBoxWrapper( group_control.child_window(auto_id="25", control_type="ComboBox")).select(" 2021/22") # Export the data group_control.child_window(auto_id="26", title="Export QA Data").click() # build output file name. # LIVE # output_file_name = os.path.normpath("//trllimited/data/INF_ScannerQA/Audit_Reports/NRCD Data/" + nation + "/" + # local_authority + "_" + year + ".csv") # test output_file_name = os.path.normpath("C:/Users/rjaques/temp/Data/" + nation + "/" + local_authority + "_" + year + ".csv") # add the year combination (year and '-' and 2 digit next year so # convert year string to numeric, add one, convert back to string and use the last 2 chars print(year) print(int(year)) print(int(year) + 1) print(str(int(year) + 1)) next_year = str(int(year) + 1)[-2:] print(next_year) survey_period = year + '-' + next_year print(survey_period) print(output_file_name) time.sleep(60) # connect to the output file name selection window and enter the name from above and save the file. app5 = Application(backend="uia").connect( title_re='Select an output file name', visible_only=True) print("\nConnect app5 filename is ", output_file_name) time.sleep(30) # app5.window(title_re='Select an output file name').print_control_identifiers() # split output_file_name into the directory path and the filename (because Mickysoft has changed the window !) # directory_path = os.path.dirname(output_file_name) # app5.window(title_re='Select an output file name') \ # .Toolbar4_Edit.set_text(directory_path) # selected_filename = os.path.basename(output_file_name) app5.window(title_re='Select an output file name') \ .File_name_Edit.set_text(output_file_name) # app5.window(title_re='Select an output file name').File_name_Edit.set_text(output_file_name) # app5.window(title_re='Select an output file name').print_control_identifiers() batch_split_button1 = app5.window(title_re='Select an output file name') \ .child_window(title='Save', auto_id='1', control_type="Button") from pywinauto.controls.win32_controls import ButtonWrapper ButtonWrapper(batch_split_button1).click() # app5.window(title_re='Select an output file name').type_keys(output_file_name, with_spaces=True) # app5.window(title_re='Select an output file name').Save.click() del app5 time.sleep(60) logger.info('waiting for ' + local_authority + ' QA output to finish') app.window(best_match='National Roads Condition Database - Version *') \ .child_window(title="NRCD") \ .wait("exists ready", timeout=10000, retry_interval=60) # app.window(best_match='National Roads Condition Database - Version *') \ # .child_window(title="NRCD") \ # .print_control_identifiers() app.window(best_match='National Roads Condition Database - Version *') \ .child_window(title="NRCD").OK.click() # Wait patiently # while nrcd_running_check("2"): # logger.info('waiting for ' + local_authority + 'QA output to finish') # time.sleep(90) logger.info(local_authority + ' QA output complete') return # back to main code block
def assign_la(app, file_path_variable): logger.info('starting local authority assignment') time.sleep(60) app.window( best_match='National Roads Condition Database', top_level_only=True).child_window(best_match='Attributes').click() time.sleep(15) group_control = app.window(best_match='National Roads Condition Database - Version *') \ .child_window(title="Local Authority Attribute", auto_id="3", control_type="Group") group_control.child_window(title="Select Batch File", auto_id="7", control_type="Button") \ .click() time.sleep(30) # app.window(best_match='National Roads Condition Database') \ # .child_window(title='NRCD').OK.click() # app.window(best_match='National Roads Condition Database - Version *') \ # .child_window(title="Local Authority Attribute", auto_id="3", control_type="Group") \ # .child_window(title="Select Batch File", auto_id="7", control_type="Button") \ # .click() filename = file_path_variable + '/BatchList.txt' print("\nfilename is ", filename) logger.info('File name is ' + filename) filename = filename.replace('/', '\\') time.sleep(15) app4 = Application(backend="uia").connect(title_re='Select a batch file', visible_only=True) print("\nConnect app4 filename is ", filename) logger.info('Connecting to the batch file selection with ' + filename) time.sleep(60) # split filename into the directory path and the filename (because Mickysoft has changed the window !) # directory_path = os.path.dirname(filename) # app4.window(title_re='Select a batch file') \ # .Toolbar4_Edit.set_text(directory_path) # selected_filename = os.path.basename(filename) app4.window(title_re='Select a batch file') \ .File_name_Edit.set_text(filename) # app4.window(title_re='Select a batch file').File_name_Edit.set_text(filename) # app4.window(title_re='Select a batch file').print_control_identifiers() # app4.window(title_re='Select a batch file').type_keys('%o') batch_splitbutton1 = app4.window(title_re='Select a batch file') \ .child_window(auto_id='1', control_type="SplitButton") from pywinauto.controls.win32_controls import ButtonWrapper ButtonWrapper(batch_splitbutton1).click() time.sleep(60) del app4 # use the location of the BatchList.txt to extract the local authority. It's two from the end. local_authority = filename.split("\\")[-2] # print(local_authority) logger.info('starting to assign attributes for ' + local_authority) # Load the human name to database name csv table lookup_table = '//trllimited/data/INF_ScannerQA/Audit_Reports/Tools/LA_to_NRCD_Name.csv' la_lookup_table = pd.read_csv(lookup_table, index_col='Audit_Report_name', dtype={'INDEX': str}) la_db_name: str = la_lookup_table.loc[local_authority, "NRCD_Name"] logger.info('DB name for the LA is ' + la_db_name) # app.window(best_match='National Roads Condition Database - Version*') \ # .child_window(best_match='Local Authority Attribute', control_type="Group").print_control_identifiers() time.sleep(15) # app.window(best_match='National Roads Condition Database - Version *') \ # .child_window(title="Local Authority Attribute", control_type="Group") \ # .child_window(best_match='3',control_type="ComboBox").type_keys("%{DOWN}") # app.window(best_match='National Roads Condition Database - Version*') \ # .child_window(best_match='Local Authority Attribute', control_type="Group") \ # .child_window(auto_id='6', control_type="ComboBox").select(la_db_name) # print(la_db_name) batch_combobox1 = app.window(best_match='National Roads Condition Database - Version*') \ .child_window(best_match='Local Authority Attribute', control_type="Group") \ .child_window(auto_id='6', control_type="ComboBox").wait('exists enabled visible ready') import pywinauto.controls.win32_controls pywinauto.controls.win32_controls.ComboBoxWrapper(batch_combobox1).select( la_db_name) batch_combobox2 = app.window(best_match='National Roads Condition Database - Version*') \ .child_window(best_match='Local Authority Attribute', control_type="Group") \ .child_window(auto_id='4', control_type="ComboBox") # .wait('exists enabled visible ready') pywinauto.controls.win32_controls.ComboBoxWrapper(batch_combobox2).select( " 2021/22") time.sleep(15) # print(survey_year) app.window(best_match='National Roads Condition Database - Version*') \ .child_window(title="Assign Local Authority", auto_id="5", control_type="Button") \ .click() logger.info('waiting for LA assignment to complete') time.sleep(60) # the following contains 10000 seconds. This is to stop the wait timing out, it retries each 90 secs # but the attributes should be finished in under 6 hours... or even one hour. app.window(best_match='National Roads Condition Database - Version*') \ .child_window(title='NRCD', control_type="Window") \ .child_window(title="OK", auto_id="2", control_type="Button") \ .wait("exists ready", timeout=10000, retry_interval=90) time.sleep(120) app.window(best_match='National Roads Condition Database - Version*') \ .child_window(title='NRCD', control_type="Window") \ .child_window(title="OK", auto_id="2", control_type="Button").click() time.sleep(60) app.window(best_match='National Roads Condition Database - Version*') \ .child_window(title="Exit", auto_id="11", control_type="Button").click() return
# logger.info('Working with ' + file_path_variable) # file_path_variable = filedialog.askdirectory(initialdir=curr_dir, # title='Please select a directory containing the data') # print("\nfile_path_variable = ", file_path_variable) from pywinauto.application import Application # For LIVE # app = Application(backend="uia").start('C:/Program Files (x86)/NRCD/NRCD.exe') # for test app = Application(backend="uia").start( 'C:/Users/rjaques/Software/NRCD/Current Version/NRCD.exe') app.window( best_match='National Roads Condition Database', top_level_only=True).child_window(best_match='SCANNER').click() time.sleep(30) main_screen = app.window( best_match='National Roads Condition Database - V*') # app.window(best_match='', top_level_only=True) \ # .print_control_identifiers() time.sleep(30) app.window(best_match='', top_level_only=True) \ .child_window(best_match='Enter System').click() time.sleep(60)
class Win32WindowMgr: """Encapsulates some calls to the winapi for window management""" def __init__(self): """Constructor""" self._handle = None self._app = None def handle(self): if self.has_handle(): return self._handle def has_handle(self): if self._handle: return True return False def clear_handle(self): self._handle = None def find_window(self, class_name, window_name=None): """find a window by its class_name""" self._handle = win32gui.FindWindow(class_name, window_name) def find_child_windows(self): LOGGER.debug('Enumerating child windows') if self._handle: win32gui.EnumChildWindows(self._handle, self._child_enum_callback, None) @staticmethod def _child_enum_callback(hwnd, lparam): LOGGER.debug('%s, %s, %s', hwnd, win32gui.GetWindowText(hwnd), win32gui.GetWindowRect(hwnd)) return 1 @staticmethod def _read_dg_version(deltagen_window): name = deltagen_window.window_text() version = name[-5:] if version == '2018x': return 2018 elif version == '2017x': return 2017 else: return 12 def find_deltagen_viewer_widget(self): """ Find the DeltaGen viewer window inside window controls """ if not self.has_handle(): return None if not self._app: try: self._app = Application().connect(handle=self._handle) except Exception as e: LOGGER.error(e, exc_info=1) return None try: dg_win = self._app.window(title_re='DELTAGEN *', depth=1, found_index=0) except Exception as e: LOGGER.error(e, exc_info=1) return None dg_version = self._read_dg_version(dg_win) viewer = None try: if dg_version == 2018: workspace = dg_win.child_window(title_re='workspace*', depth=1) viewer = workspace.child_window(title='pGLWidgetWindow', depth=2, found_index=0) else: workspace = dg_win.child_window(title='workspace', depth=1) viewer_window = workspace.child_window(title='untitled', depth=1, class_name='QWidget', found_index=0) search_terms = ( 'pGLWidget', # DeltaGen > 2017x '' # DeltaGen 12.2 ) for term in search_terms: if viewer_window.child_window(title=term, depth=1, class_name='QWidget', found_index=0).exists(): viewer = viewer_window.child_window( title=term, depth=1, class_name='QWidget', found_index=0) break if not viewer: return except Exception as e: LOGGER.error(e, exc_info=1) return None return viewer def _window_enum_callback(self, hwnd, wildcard): """Pass to win32gui.EnumWindows() to check all the opened windows""" if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None: self._handle = hwnd def find_window_wildcard(self, wildcard): """find a window whose title matches the wildcard regex""" self._handle = None win32gui.EnumWindows(self._window_enum_callback, wildcard) def set_foreground(self): """put the window in the foreground""" if self._handle: win32gui.SetForegroundWindow(self._handle)
def run_declaration_app(path:str, data_json: str): print("Read input params") print('First arg - path to Declaration 2018') print('Second arg - data json for Declaration 2018') ## todo проверка входных параметров data = json.loads(data_json) number_i= data['declaration']['block1']['number_i'] # 0101 number_k= int(data['declaration']['block1']['number_k']) # 0 oktmo = data['declaration']['block1']['oktmo'] # '04701000' radio_btn1 = data['declaration']['block1']['radio_btn1'] # 'Иное физическое лицо' radio_btn2 = data['declaration']['block1']['radio_btn2'] # 'Лично' last_name = data['declaration']['block2']['lastname'] # 'ИВАНОВА' first_name = data['declaration']['block2']['firstname'] # 'ЮЛИЯ' sir_name = data['declaration']['block2']['sirname'] # ВАЛЕРЬЕВНА inn = data['declaration']['block2']['inn'] # '780204893183' birth_place = data['declaration']['block2']['birth_place'] # 'Г.РОСТОВ-НА-ДОНУ' birth_date = data['declaration']['block2']['birth_date'] # '02.06.1982' phone = data['declaration']['block2']['phone'] # '89135555555' type_doc = data['declaration']['block2']['type_doc'] # '21' doc_number = data['declaration']['block2']['doc_number'] # '04 09 934566' doc_from = data['declaration']['block2']['doc_from'] # 'ТП №75 ОТДЕЛА УФМС РОССИИ ПО САНКТ-ПЕТЕРБУРГУ И ЛЕНИНГРАДСКОЙ ОБЛ. В ФРУНЗЕНСКОМ Р-НЕ ГОР.САНКТ-ПЕТЕРБУРГА КОД ПОДРАЗДЕЛЕНИЯ 780-075' doc_date = data['declaration']['block2']['doc_date'] # '02.03.2002' money_source_company = data['declaration']['block3']['money_source_company'] # '04701000' # '2464001001' # '2464231675' # PRAVOCARD money_dec = data['declaration']['block3']['money_dec'] # '14316' money_source = data['declaration']['block3']['money_source'] money_source_bottom_table = data['declaration']['block3']['money_source_bottom_table'] code_number_object = data['declaration']['block5']['code_number_object'] # 1 sign_taxplayer = data['declaration']['block5']['sign_taxplayer'] # 1 object_name = data['declaration']['block5']['object_name'] # 2 object_data = data['declaration']['block5']['object_data'] app = Application(backend='uia').start(path) main_window = app.window(title='Без имени - Декларация 2018') main_window.set_focus() def _select_tab(num: int): step = int(main_window.rectangle().height() / 9) offset = step * num navigation_panel.click_input(coords=(0, offset)) def _select_tab_toolpanel(num: int): step = int(main_window.rectangle().height() / 9) offset = step * num tool_panel.click_input(coords=(0, offset)) def _select_radio(group: str, v: str): group = main_window.window(title=' ' + group) c = group.window(title=v) c.click_input() def _type_to_onlyone_input_by_index(group: str, text: str, class_name: str): parent = main_window.window(title=group) child = parent.child_window() child.set_text(text) def _type_to_input_by_index(group: str, ind: int, text: str, class_name: str): inpts = main_window.window(title=' ' + group).descendants(class_name=class_name) inpts[ind].set_text(text) def _type_to_input_by_index_mask(group: str, ind: int, text: str, class_name: str): inpts = main_window.window(title=' ' + group).descendants(class_name=class_name) inpts[0].set_text(text) def _set_spinner(group: str, ind: int, v: int): group = main_window.window(title=' ' + group) bs = group.descendants() b = bs[ind] b.set_text(v) def _select_from_dict(group: str, win_title: int, v: str): group = main_window.window(title=' ' + group) b = group.window(title='...') b.click_input() dw = app.window(title=win_title) l = dw.window(class_name="TListView") l.set_focus() vl = l.window(title=v) for _ in range(1000): try: #if vl.is_visible(timeout=0.5): vl.click_input() break except ElementNotFoundError: send_keys('{PGDN}') ok_b = dw.window(title='Да') ok_b.click_input() def _check_checkbox(group: str, name: str): cb = main_window.window(title=name) cb.click_input() labels2indTab1 = { 'Номер инспекции': ('Общая информация', 'Справочник инспекций', 0), 'Номер корректировки': ('Общая информация', 4, 0), 'ОКТМО': ('Общая информация', 0, 0), 'Индивидуальный предприниматель': ('Признак налогоплательщика', None, 0), 'Глава фермерского хозяйства': ('Признак налогоплательщика', None, 0), 'Частный нотариус': ('Признак налогоплательщика', None, 0), 'Адвокат': ('Признак налогоплательщика', None, 0), 'Иное физическое лицо': ('Признак налогоплательщика', None, 0), 'Арбитражный управляющий': ('Признак налогоплательщика', None, 0), 'Учитываемые "справками о доходах физического лица", доходы по договорам': ('Имеются доходы', None, 0), 'В иностранной валюте': ('Имеются доходы', None, 0), 'От предпринимательской деятельности': ('Имеются доходы', None, 0), 'Лично': ('Достоверность подтверждается', None, 0), 'Представителем - ФЛ': ('Достоверность подтверждается', None, 0), 'ФИО': ('Достоверность подтверждается', 1, 0), 'Документ': ('Достоверность подтверждается', 0, 0), 'Фамилия': ('Ф.И.О.', 4, 1), 'Имя': ('Ф.И.О.', 3, 1), 'Отчество': ('Ф.И.О.', 2, 1), 'ИНН': ('Ф.И.О.', 1, 1), 'Дата рождения': ('Ф.И.О.', 0, 1), 'Место рождения': ('Ф.И.О.', 0, 1), 'Вид документа': ('Сведения о документе, удостоверяющем личность', 'Справочник видов документов', 1), 'Серия и номер': ('Сведения о документе, удостоверяющем личность', 0, 1), 'Дата выдачи': ('Сведения о документе, удостоверяющем личность', 0, 1), 'Кем выдан': ('Сведения о документе, удостоверяющем личность', 1, 1), 'Контактный телефон': ('Контактный телефон', 0, 1), 'Наименование источника выплаты': ('Наименование источника выплаты', 0, 0), 'ИНН Источника выплаты': ('ИНН', 1, 0), 'КПП Источника выплаты': ('КПП', 2, 0), 'ОКТМО Источника выплаты': ('ОКТМО', 3, 0), 'Чекбокс Источник выплаты1': ('Расчет стандартных вычетов вести по этому источнику', None, 0), 'Чекбокс Источника выплаты2': ('Источник является инвестиционным товариществом', None, 0), 'Код дохода': ('Сведения о полученном доходе', 'Справочник видов доходов', 2) } def select_from_dict(name: str, v: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _select_from_dict(group, ind, v) def select_from_dict_from_modal_window(name: str, v: str): group, ind, tb = labels2indTab1[name] _select_from_dict_from_modal_window(group, ind, v) def set_spinner(name: str, v: int): group, ind, tb = labels2indTab1[name] _select_tab(tb) _set_spinner(group, ind, v) def fill_only_one_input(name: str, v: str, class_name: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _type_to_onlyone_input_by_index(group, v, class_name) def fill_input(name: str, v: str, class_name: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _type_to_input_by_index(group, ind, v, class_name) def select_radio(name: str): group, _, tb = labels2indTab1[name] _select_tab(tb) _select_radio(group, name) def select_checkbox(name: str): group, _, tb = labels2indTab1[name] _select_tab(tb) _check_checkbox(group, name) def fill_input_mask(name: str, v: str, class_name: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _type_to_input_by_index_mask(group, ind, v, class_name) print('Start new decl filling....') print('Block №1 - Задание условий') navigation_panel = main_window.descendants(class_name="TPanel")[1] select_from_dict('Номер инспекции', number_i) set_spinner('Номер корректировки', number_k) fill_input('ОКТМО', oktmo, 'TMaskedEdit') select_radio(radio_btn1) ## todo проверка - добавляется количество заполняемых данных ## первое устанавливается по-умолчанию ## select_checkbox('Учитываемые "справками о доходах физического лица", доходы по договорам') select_radio(radio_btn2) print('Block №1 - Сведения о декларанте') _select_tab(1) fill_input('Фамилия', last_name, 'TMaskedEdit') fill_input('Имя', first_name,'TMaskedEdit') fill_input('Отчество', sir_name, 'TMaskedEdit') fill_input('ИНН', inn , 'TMaskedEdit') fill_input('Место рождения', birth_place, 'TMaskedEdit') fill_input('Дата рождения', birth_date, 'TTestMaskD') fill_only_one_input('Контактный телефон', phone, 'TMaskedEdit') select_from_dict('Вид документа', type_doc) fill_input_mask('Серия и номер', doc_number , 'TMaskedDocEdit') fill_input_mask('Кем выдан', doc_from , 'TMaskedEdit') fill_input('Дата выдачи', doc_date, 'TTestMaskD') print('Block №1 - Доходы, полученные в РФ') _select_tab(2) ## todo пока клик настроен только на кнопку 13 в панели ## она устанавливается по-умолчанию print('Add money source') add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[8].click_input(coords=(10, 55)) print('Source money Modal window filling') dw = app.window(title='Источник выплаты') inner_edit = dw.window(class_name="TPanel").descendants(); inner_edit[1].type_keys(money_source_company[0]) inner_edit[3].type_keys(money_source_company[1]) inner_edit[4].type_keys(money_source_company[2]) ## todo проверить варианты ввода на русском языке ## пока проблема inner_edit[5].type_keys(money_source_company[3]) inner_checkbox = dw.window(class_name="TPanel").descendants(class_name="TCheckBox") inner_checkbox[1].click_input() ok_b = dw.window(title='Да') ok_b.click_input() edit_form = add_money_source_allpanel.descendants(class_name='TMaskedEdit') edit_form[1].set_text(money_dec) print('Info money source Modal Window filling') for money_source_item in money_source: add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[8].click_input(coords=(10, 155)) finance_buttons = app.window(title='Сведения о доходе').descendants(class_name="TButton") finance_buttons[3].click_input(); print('Open dictionary of the type of money') dw = app.window(title='Справочник видов доходов') l = dw.window(class_name="TListView") l.set_focus() vl = l.window(title= money_source_item['code']) for _ in range(1000): try: #if vl.is_visible(timeout=0.5): vl.click_input() break except ElementNotFoundError: send_keys('{PGDN}') ok_b = dw.window(title='Да') ok_b.click_input() print('Dictionary of the type of money source') edit_buttons = app.window(title='Сведения о доходе').descendants(class_name="TMaskedEdit") edit_buttons[2].set_text( money_source_item['money_sum']) edit_buttons[1].set_text( money_source_item['month']) app.window(title='Сведения о доходе').window(title='Да').click_input() print('Bottom table filling') add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[8].click_input(coords=(10, 455)) finance_buttons = app.window(title='Вычеты, указанные в разделе 3 справки 2-ндфл').descendants(class_name="TButton") finance_buttons[2].click_input() dw = app.window(title='Справочник видов вычетов') l = dw.window(class_name="TListView") l.set_focus() vl = l.window(title= money_source_bottom_table['code']) for _ in range(1000): try: #if vl.is_visible(timeout=0.5): vl.click_input() break except ElementNotFoundError: send_keys('{PGDN}') ok_b = dw.window(title='Да') ok_b.click_input() print('Get dictionary another money source') edit_buttons = app.window(title='Вычеты, указанные в разделе 3 справки 2-ндфл').descendants(class_name='TMaskedEdit') edit_buttons[0].set_text(money_source_bottom_table['money']) # 16800 app.window(title='Вычеты, указанные в разделе 3 справки 2-ндфл').window(title='Да').click_input() print("Block 3") _select_tab(5) check_boxes = main_window.descendants(class_name='TCheckBox') check_boxes[0].click_input() add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[0].click_input(coords=(10, 55)) print('Objects Data Modal Window filling') combo_boxes = app.window(title='Данные объекта').descendants(class_name='TComboBox') # Код номера объекта Кадастровый номер combo_boxes[0].click_input() cmb1 = combo_boxes[0].descendants() cmb1[int(code_number_object)].click_input() # 1 - Кадастровый номер # Признак налогоплательщика Собственник объекта combo_boxes[1].click_input() cmb1 = combo_boxes[1].descendants() cmb1[int(sign_taxplayer)].click_input() # 0 - Родитель несовершеннолетнего собственника объекта # 1 - Собственник объекта # Наименование объекта combo_boxes[2].click_input() cmb1 = combo_boxes[2].descendants() cmb1[int(object_name)].click_input() # 0 - Земельный участок для индивидуального жилищного строительства # 1 - Жилой дом # 2 - Квартира masked_edits = app.window(title='Данные объекта').descendants(class_name='TMaskedEdit') masked_edits[5].set_text(object_data['object_number']) masked_edits[4].set_text(object_data['object_address']) masked_edits[1].set_text(object_data['object_sum']) masked_edits[0].set_text(object_data['object_del']) masked_date_edits = app.window(title='Данные объекта').descendants(class_name='TTestMaskD') masked_date_edits[1].set_text(object_data['object_date']) app.window(title='Данные объекта').window(title='Да').click_input() ### Сохранить декларацию manage_btns = main_window.descendants(class_name='TToolBar') manage_btns[1].click_input() print('Choose folder to save...') dw = app.window(title='Обзор папок') l = dw.descendants()[1] #todo перенести в параметры item = l.get_item([r'\Рабочий стол\dec']) item.select() dw.descendants(class_name='Button')[0].click_input() ### Last Step app.window(title='Декларация 2018').descendants(class_name='Button')[0].click_input() ## todo проверка на ошибку - куча всплывающих окон может быть #app.window(title='Декларация 2018').descendants(class_name='Button')[0].click_input() print('Declaration is Ready!') app.kill()
import logging from pywinauto import actionlogger from pywinauto import Application import argparse parser = argparse.ArgumentParser() parser.add_argument("--log", help = "enable logging", type=str, required = False) args = parser.parse_args() actionlogger.enable() logger = logging.getLogger('pywinauto') if args.log: logger.handlers[0] = logging.FileHandler(args.log) app = Application(backend='uia').start(r'mspaint.exe') dlg = app.window(title_re='.* - Paint') # File->Open menu selection dlg.File_tab.click() dlg.child_window(title='Open', control_type='MenuItem', found_index=0).invoke() # handle Open dialog file_name_edit = dlg.Open.child_window(title="File name:", control_type="Edit") file_name_edit.set_text('walter_cat.jpg') # There are 2 Open buttons: # dlg.Open.Open.click() will call drop down list of the file name combo box. # The child_window statement is just copied from print_control_identifiers(). dlg.Open.child_window(title="Open", auto_id="1", control_type="Button").click() dlg.ResizeButton.click() dlg.ResizeAndSkew.Pixels.select()
def auto_install(self): choose = self.choose start_time = (strftime("%H:%M", localtime())) # 获取运行程序时的开始时间 failure = [] # 保存安装失败的软件名称 menu = load_menu() # 读取安装目录下的menu.txt获取需要安装的文件 menu_change = menu.copy() for each in menu: labelframe1 = tk.LabelFrame(self.root, text=f'安装进度(第{menu.index(each) + 1}个,共{len(menu)}个)', height=80, width=300) # 信息区 labelframe1.grid(row=1, column=0, columnspan=10, padx=10, pady=10) labelframe1.propagate(0) # 使组件大小不变,此时width才起作用 tk.Label(labelframe1, text=f"正在安装{format_menu(each.split())[0]}...", font=(', 11')).pack(fill="both", expand="yes") if each == 'QQ': main_window = ["腾讯QQ安装向导", "win32", "QQ"] step = {0: ["自定义选项", 'click', 15], 1: ["添加到快速启动栏", 'click', 6], 2: ["开机自动启动", 'click', 6], 3: ['', 'edit', 6], 4: ["立即安装", 'click', 6], 5: ["完成安装", 'click', 40]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'QQ', 'QQ.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=3): kill_program(main_window[2]) # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'Wechat': main_window = ["微信安装向导", "uia", "微信"] step = {0: ["更多选项", 'click', 40], 1: ["程序安装目录", 'edit', 6], 2: ["安装微信", 'click', 6], 3: ['开始使用', 'click', 40]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'wechat', 'wechat.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each)): kill_program(main_window[2]) # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'Dtalk': main_window = ["钉钉 安装", "win32"] step = {0: ["下一步(&N) >", 'click', 50], 1: ["", 'edit', 6], 2: ["下一步(&N) >", 'click', 6], 3: ["运行 钉钉(&R)", 'click', 40], 4: ["完成(&F)", 'click', 6]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'Dtalk', 'Dtalk.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=1): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'Winrar': main_window = ["WinRAR 5.91", "win32", 10] step = {0: ["", "Edit", 'edit', 6], 1: ["安装", "Button", 'click', 6]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'Winrar', 'Winrar.exe')) sleep(2) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=0, special=True): time = 6 while time >= 0: try: temp = Application().connect(title="WinRAR 简体中文版安装") except: sleep(1) time -= 1 else: # 未抛出异常时说明程序成功链接 for button in ["确定", "完成"]: temp2 = temp.window(title='WinRAR 简体中文版安装').child_window(title=button).wait('ready', timeout=30) temp2.click() break # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'LMsoft': main_window = 'uia' step = {0: ["原创工具", 'click', 10], 1: ["流氓软件免疫", 'click', 5], 2: ["一键免疫", 'click', 8], 3: ["确定", 'click', 3], 4: ["确定", 'click', 10] } sleep_time = [1, 5, 2, 5, 2] program = Application(backend=main_window).start( join(getcwd(), 'app_pkg', each, each)) if install_from_topwindow(window_backend=main_window, step=step, program=program, install_path=join(choose, each), sleep_time=sleep_time): program.kill() txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each in ['VCRedist', 'DX', 'NF3']: main_window = "win32" step = {0: ["确定", 'click', 10], 1: ["是(&Y)", 'click', 10]} sleep_time = [1, 0] program = Application(backend=main_window).start( join(getcwd(), 'app_pkg', each, each)) if install_from_topwindow(window_backend=main_window, step=step, program=program, install_path=join(choose, each), sleep_time=sleep_time): ok_dict = {'DX': 'DirectX 9.0c 安装完成!程序即将退出', 'VCRedist': 'Visual C++ 运行库 安装完成!程序即将退出', 'NF3': '.Net Framework 安装完成!程序即将退出'} # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) time = 60 while time >= 0: try: if program.window(title_re='信息').child_window(title=ok_dict[each]).exists(): break except: sleep(1) time -= 1 program.window(title_re='信息').child_window( title=ok_dict[each]).wait('ready', timeout=80) program.window(title_re='信息').child_window( title="确定").click_input() else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'OFFICE2013': main_window = [ "Microsoft Office Professional Plus 2013", "uia"] step = {0: ["我接受此协议的条款", "CheckBox", 'click', 20], 1: ["继续", "Button", 'click', 6], 2: ["自定义", "Button", 'click', 6], 3: ["Microsoft Access", "MenuItem", 'click', 6], 4: ["不可用", "Button", 'click', 6], 5: ["Microsoft InfoPath", "MenuItem", 'click', 6], 6: ["不可用", "Button", 'click', 6], 7: ["Microsoft Lync", "MenuItem", 'click', 6], 8: ["不可用", "Button", 'click', 6], 9: ["Microsoft OneNote", "MenuItem", 'click', 6], 10: ["不可用", "Button", 'click', 6], 11: ["Microsoft Outlook", "MenuItem", 'click', 6], 12: ["不可用", "Button", 'click', 6], 13: ["Microsoft Publisher", "MenuItem", 'click', 6], 14: ["不可用", "Button", 'click', 6], 15: ["Microsoft SkyDrive Pro", "MenuItem", 'click', 6], 16: ["不可用", "Button", 'click', 6], 17: ["Microsoft Visio Viewer", "MenuItem", 'click', 6], 18: ["不可用", "Button", 'click', 6], 19: ["文件位置", "TabItem", 'click', 6], 20: ["", "Edit", 'edit', 10], 21: ["立即安装", "Button", 'click', 6]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'OFFICE2013', 'setup.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=20, special=True): program.window(title_re='Microsoft Office Professional Plus 2013').child_window(title="继续联机", control_type="Button" ).wait('ready', timeout=600) program.window(title_re='Microsoft Office Professional Plus 2013')[ '关闭Button'].click_input() # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) office_crack(choose) # 激活office else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == "WPS": sleep_time = [5, 1, 1, 1] # 各图片的等待时间 grayscale = [True, True, True, False] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [-200, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", 'WPS', 'wpssetup_k56008174_281235.exe')) # 打开指定的安装程序 png_file_name = "_shot" if system_info() == "10" else "_shot_win7" result = install_from_png(app_name=each, edit_index=2, png_file_name=png_file_name, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each == '360drv': main_window = ["欢迎使用 360驱动大师", "uia"] step = {0: ["已经阅读并同意", 'CheckBox', 'click', 10], 1: ["", 'Edit', 'edit', 6], 2: ["安装完成后打开360驱动大师", 'CheckBox', 'click', 6], 3: ["立即安装", 'Button', 'click', 6]} sleep_time = [3] # 各图片的等待时间 grayscale = [True] # 各图片是否使用灰度搜索 skewing = [[0, 0]] # x、y坐标偏移 program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, each)) result = install_from_png(app_name=each, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing) # 第一个按钮获取不到用png图片匹配 if result: if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=1, special=True): # 图片匹配成功后再用pywinauto控制 txt_change(prom_name=each, menu_change=menu_change) else: # 安装失败记录安装失败程序 failure.extend(format_menu(each.split())) else: failure.extend(format_menu(each.split())) if each == "Chrome": program = Application(backend='win32').start( join(getcwd(), 'app_pkg', each, each)) txt_change(prom_name=each, menu_change=menu_change) while True: if not program.is_process_running(): break kill_program("欢迎使用 Chrome - Google Chrome") if each == "2345explorer": sleep_time = [5, 1] # 各图片的等待时间 grayscale = [False, False] # 各图片是否使用灰度搜索 skewing = [[300, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, '2345explorer_k56008174.exe')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=0, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title=['2345网址导航-开创中国百年品牌(已创建11年整) - 2345加速浏览器 10.14', '网络不稳定或断网 - 2345加速浏览器 10.14'], time=30) else: failure.extend(format_menu(each.split())) if each == "TXvideo": main_window = ["腾讯视频 2020 安装程序 ", "win32"] step = {0: ["自定义安装", 'click', 30], 1: ["开机自动启动", 'click', 6], 2: ["", 'edit', 6], 3: ["立即安装", 'click', 8], 4: ["立即体验", 'click', 90]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, each)) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=2): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) kill_program(title='腾讯视频') else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == "IQIYI": main_window = ["爱奇艺 安装向导", "win32"] step = {0: ["阅读并同意", 'click', 30], 1: ["", 'edit', 6], 2: ["立即安装", 'click', 6], 3: ["完成", 'click', 90]} Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, 'iqiyi_k56008174_107328.exe')) time = 5 while time >= 0: try: program = Application(backend=main_window[1]).connect( title_re=main_window[0]) # 直接打开的程序对象不能直接使用需要重新链接 except: sleep(1) time -= 1 else: if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=1): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: # 安装失败记录安装失败程序 failure.extend(format_menu(each.split())) break if each == "PSCS3": main_window = ["安装 - Adobe Photoshop CS3 Extended", "win32"] step = {0: ["下一步(&N) >", "TButton", 'click', 10], 1: [r"C:\Program Files (x86)\Adobe\Adobe Photoshop CS3", "TEdit", 'edit', 6], 2: ["下一步(&N) >", "TButton", 'click', 6], 3: ["下一步(&N) >", "TButton", 'click', 6], 4: ["安装(&I)", "TButton", 'click', 6], 5: ["完成(&F)", "TButton", 'click', 60]} Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, each)) time = 5 while time >= 0: try: program = Application(backend=main_window[1]).connect( title='安装') # 直接打开的程序对象不能直接使用需要重新链接 except: sleep(1) time -= 1 else: if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=100, special=True): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: # 安装失败记录安装失败程序 failure.extend(format_menu(each.split())) break if each == "PSCC2018": # PSCC2018打开自动安装不需要任何按钮 if "PSCS3" in menu: # 防止装完PSCS3马上打开程序报错 sleep(5) ps_path = join(getcwd(), "app_pkg", each, 'Set-up') copy(ps_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 10 while time >= 0: try: ps_cc = Application().connect(path=paste()) except: sleep(1) time -= 1 else: break while True: if not ps_cc.is_process_running(): break else: sleep(2) txt_change(prom_name=each, menu_change=menu_change) kill_program(title='Adobe Photoshop CC 2018') ps_crack() if each == "PRCC2018": # PRCC2018打开自动安装不需要任何按钮 pr_path = join(getcwd(), "app_pkg", each, 'Set-up') copy(pr_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 10 while time >= 0: try: pr_cc = Application().connect(path=paste()) except: sleep(1) time -= 1 else: break while True: if not pr_cc.is_process_running(): break else: sleep(2) txt_change(prom_name=each, menu_change=menu_change) kill_program(title='Adobe Premiere Pro CC 2018') pr_crack() if each == "163music": sleep_time = [5, 1, 1, 1, 1, 5] # 各图片的等待时间 grayscale = [True, True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [0, 0], [-230, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, each)) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=3, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) time = 5 while time >= 0: try: Application(backend='uia').connect(title='网易云音乐') except: sleep(1) time -= 1 else: system('taskkill /IM cloudmusic.exe /F') sleep(3) break else: failure.extend(format_menu(each.split())) if each == "QQmusic": sleep_time = [5, 1, 1, 1, 5] # 各图片的等待时间 grayscale = [True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [-230, 0], [0, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, 'QQMusic_YQQFullStack')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=2, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title='QQ音乐', backend='uia') else: failure.extend(format_menu(each.split())) if each == "Kugou": sleep_time = [5, 1, 1, 1, 1, 1, 10] # 各图片的等待时间 grayscale = [True, True, True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [-250, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, 'kugou_k56008174_306395')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=1, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title='酷狗音乐', backend='uia') else: failure.extend(format_menu(each.split())) if each == "Xunlei": sleep_time = [3, 3] # 各图片的等待时间 grayscale = [True, True] # 各图片是否使用灰度搜索 skewing = [[-50, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, each)) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=0, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title='迅雷', backend='uia') else: failure.extend(format_menu(each.split())) if each == "SougouPY": sleep_time = [5, 1, 1, 1, 1, 8] # 各图片的等待时间 grayscale = [True, True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [0, 0], [ 70, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, each)) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=3, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each == "2345pinyin": sleep_time = [5, 1, 1, 10] # 各图片的等待时间 grayscale = [False, True, True, True] # 各图片是否使用灰度搜索 skewing = [[50, 0], [0, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, '2345pinyin_k56008174.exe')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=0, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each == "3DMAX2014": step = {0: ["ListBox3", 'click', 30], 1: ["我接受Button", 'click', 6], 2: ["下一步Button", 'click', 6], 3: ["序列号:Edit", '666', 'edit', 6], 4: ["Edit2", '69696969', 'edit', 6], 5: ["产品密钥:Edit5", '128F1', 'edit', 6], 6: ["下一步Button", 'click', 6], 7: ["安装路径:Edit", join(choose, each), 'edit', 6], 8: ["安装Button", 'click', 6]} setup_path = join(getcwd(), "app_pkg", each, "Setup.exe") copy(setup_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 20 while time >= 0: try: program = Application().connect(title="Autodesk 3ds Max 2014") except: sleep(1) time -= 1 else: break if simple_install(window_backend='win32', step=step, program=program): while True: try: temp = Application().connect(title_re='文件正在使用') if temp.top_window().window(title='忽略(&I)').exists(): temp.top_window()['忽略(&I)'].click_input() except: pass if program.top_window().child_window(title="完成").exists(): program.top_window().child_window(title="完成").wait("ready", timeout=10) program.top_window()['完成'].click_input() txt_change(prom_name=each, menu_change=menu_change) break else: sleep(3) cra_3dmax(choose, each) else: failure.extend(format_menu(each.split())) if each == "CAD2014": step = {0: ["ListBox3", 'click', 30], 1: ["我接受Button", 'click', 6], 2: ["下一步Button", 'click', 6], 3: ["序列号:Edit", '666', 'edit', 6], 4: ["Edit2", '69696969', 'edit', 6], 5: ["产品密钥:Edit5", '001F1', 'edit', 6], 6: ["下一步Button", 'click', 6], 7: ["安装路径:Edit", join(choose, each), 'edit', 6], 8: ["安装Button", 'click', 6]} setup_path = join(getcwd(), "app_pkg", each, "Setup.exe") copy(setup_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 20 while time >= 0: try: program = Application().connect(title="Autodesk® AutoCAD® 2014") except: sleep(1) time -= 1 else: break if simple_install(window_backend='win32', step=step, program=program): while True: try: temp = Application().connect(title_re='文件正在使用') if temp.top_window().window(title='忽略(&I)').exists(): temp.top_window()['忽略(&I)'].click_input() except: pass if program.top_window().child_window(title="完成").exists(): program.top_window().child_window(title="完成").wait("ready", timeout=10) program.top_window()['完成'].click_input() txt_change(prom_name=each, menu_change=menu_change) break else: sleep(3) cra_3dmax(choose, each) else: failure.extend(format_menu(each.split())) if each == "CAD2007": program = Application().start(join(getcwd(), "app_pkg", each, 'setup')) if program.top_window()['确定Button'].wait("ready", timeout=10) and program.top_window()[ '确定Button'].exists(): sleep(1) program.top_window()['确定Button'].click_input() time = 10 while time >= 0: try: program = Application().connect(title="AutoCAD 2007 安装") except: sleep(1) time -= 1 else: break step = {0: ["Button2", 'click', 10], 1: ["RadioButton2", 'click', 6], 2: ["Button0", 'click', 6], 3: ["Edit1", '000', 'edit', 6], 4: ["Edit2", '00000000', 'edit', 6], 5: ["Button1", 'click', 6], 6: ["Edit1", "admin", 'edit', 6], 7: ["Edit2", "admin", 'edit', 6], 8: ["Edit3", "admin", 'edit', 6], 9: ["Edit4", "admin", 'edit', 6], 10: ["Edit5", "admin", 'edit', 6], 11: ["Button1", "click", 6], 12: ["Button1", "click", 6], 13: ["Button1", "click", 6], 14: ["Edit", join(choose, each), 'edit', 6], 15: ["Button1", "click", 6], 16: ["Button1", "click", 6], 17: ["Button1", "click", 6]} sleep_time = [1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 3, 3, 0, 3, 3, 3] if simple_install(window_backend="win32", step=step, program=program, sleep_time=sleep_time): sleep(5) try: Application().connect(title="AutoCAD 2007 安装程序") except: failure.extend(format_menu(each.split())) break sleep(2) time = 300 while time >= 0: try: program = Application().connect(title="AutoCAD 2007 安装程序") if program.top_window()['完成(&F)'].exists(): break except: sleep(1) time -= 1 step = {0: ["CheckBox", 'click', 8], 1: ["Button1", 'click', 6]} simple_install(window_backend="win32", step=step, program=program) txt_change(prom_name=each, menu_change=menu_change) cad2007_cra(choose) else: failure.extend(format_menu(each.split())) if each == "T20": program = Application().start(join(getcwd(), "app_pkg", each, 'setup')) time = 20 while time >= 0: if program.top_window()["我接受许可证协议中的条款((&A)RadioButton"].exists(): break sleep(1) time -= 1 step = {0: ["我接受许可证协议中的条款((&A)RadioButton", 'click', 10], 1: ["下一步(&N) >Button", 'click', 6], 2: ["浏览(&R)...Button", 'click', 6], 3: ["路径(&P):Edit", join(choose, each), 'edit', 6], 4: ["确定Button", 'click', 6], 5: ["下一步(&N) >Button", 'click', 6], 6: ["下一步(&N) >Button", 'click', 6]} sleep_time = [0, 2, 1, 0, 0.5, 0.5, 0] if simple_install(window_backend="win32", step=step, program=program, sleep_time=sleep_time): time = 60 while time >= 0: try: if program.top_window()['InstallShield Wizard 完成'].exists(): break except: sleep(1) time -= 1 step = {0: ["完成Button", 'click', 10]} if simple_install(window_backend="win32", step=step, program=program): t20_cra(choose) txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) end_time = strftime("%H:%M", localtime()) # 获取程序安装结束时的时间 menu = format_menu(menu) labelframe1 = tk.LabelFrame( self.root, text="", height=80, width=300) # 信息区 labelframe1.grid(row=1, column=0, columnspan=10, padx=10, pady=10) labelframe1.propagate(0) # 使组件大小不变,此时width才起作用 if len(failure) != 0: tk.Label(labelframe1, text=f"程序安装完毕,用时{running_time(start_time, end_time)}分钟,共选择了{len(menu)}个软件,\n安装失败的软件为:{','.join(failure)}", font=(', 8')).pack(fill="both", expand="yes") else: tk.Label(labelframe1, text=f"程序安装完毕,用时{running_time(start_time, end_time)}分钟,共选择了{len(menu)}个软件", font=(', 10')).pack(fill="both", expand="yes")
def login(): global app global main_win # Programatically kills then starts and signs into zoom all using the api subprocess.call( "taskkill /IM \"Zoom.exe\" /F" ) # If this breaks, you could use $> tasklist | more and grep the output to a file then parse it for the word "zoom" to get the process ID and kill it that way. subprocess.call("taskkill /IM \"chrome.exe\" /F") # launch zoom with win32 api app = Application(backend="uia").start("zoom --login") main_win = app.window(title='Zoom') # if the app opens to the "zoom cloud meetings" welcome screen, lets sign in try: # defines this screen: "JoinMeetingANDSignIn_Screen.png" as the window JoinMeetingANDSignIn_Screen = app.window(title='Zoom Cloud Meetings') time.sleep(0.5) # selects the control identifier for the "sign in" button and activates it startscreen = JoinMeetingANDSignIn_Screen.child_window( title="Sign In", control_type="Button") startscreen.click() except: pass try: SigninWithGoogleScreen = app.window(title='Zoom Cloud Meetings') signInWithGoogle = SigninWithGoogleScreen.child_window( title="Sign In with Google", control_type="Button") signInWithGoogle.click() if "chrome.exe" in (p.name() for p in psutil.process_iter()): print("Chromium.exe process is running") # processID = [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'Sign In - Google Accounts' in p.info['name']] # print(processID) time.sleep(4) # time.sleep(2) keyboard.press("tab") time.sleep(0.3) keyboard.press("tab") time.sleep(0.6) keyboard.press("enter") time.sleep(0.4) keyboard.press("enter") # time.sleep(3) keyboard.press("tab") time.sleep(0.4) keyboard.press("tab") time.sleep(0.4) keyboard.press("enter") time.sleep(0.4) keyboard.press("enter") # pywinauto.application.findwindows.find_element("Edge") # chrome = Application(backend="uia").connect(path="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe") # chromewindow = chrome.top_window() # mainwin_edge = edge.window(title='Sign In - Google Accounts and') # todo return control identifiers or write to file and read the file # #todo IF control identifiers has attribute "child_window(title="Sign In", control_type="Button")" : # #todo check IF control identifiers has attribute "title="Sign In with Google", control_type="Button" # #todo check if browser has opened # # #todo possibly try again before printing error. Make a counter and print on the second time through except: pass return app
# 获取警告弹窗文本 import subprocess import uiautomation from pywinauto import Application py = Application().connect(title_re="编辑工况") app = py.window(title_re="编辑工况") app.print_control_identifiers()
- Windows 10 (may work on Win7+) - pywinauto 0.6.1+ This example opens "Control Panel", navigates to "Installed Updates" page and lists all updates (for all apps) as well as OS Windows updates only. """ from __future__ import print_function from pywinauto import Application # Open "Control Panel" Application().start('control.exe') app = Application(backend='uia').connect(path='explorer.exe', title='Control Panel') # Go to "Programs" app.window(title='Control Panel').ProgramsHyperlink.invoke() app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0) # Go to "Installed Updates" app.window(title='Programs').child_window(title='View installed updates', control_type='Hyperlink').invoke() app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0) list_box = app.InstalledUpdates.FolderViewListBox # list all updates items = list_box.descendants(control_type='ListItem') all_updates = [item.window_text() for item in items] print('\nAll updates ({}):\n'.format(len(all_updates))) print(all_updates) # list updates from "Microsoft Windows" group only
chrome_dir + ' --force-renderer-accessibility --incognito --start-maximized ' 'https://accounts.google.com/ServiceLogin?service=wise&passive=1209600&continue=https:' '//drive.google.com/?urp%3Dhttps://www.google.ru/_/chrome/newtab?espv%253D2%2526ie%253DUT%23&followup=' 'https://drive.google.com/?urp%3Dhttps://www.google.ru/_/chrome/newtab?espv%253D2%2526ie%253DUT' '<mpl=drive&emr=1#identifier') # wait while a page is loading chrome[tab_log_in].child_window(title_re='Reload.*', control_type='Button').wait('visible', timeout=10) ch_window = chrome[tab_drive].child_window(title="Google Chrome", control_type="Custom") # log in chrome.window().type_keys('TestPywinauto{ENTER}') # username chrome[tab_log_in].child_window(title="Google Chrome", control_type="Custom").\ child_window(title="Back", control_type="Image").wait(wait_for='visible', timeout=10) chrome.window().type_keys('testpywinauto123{ENTER}') # password ch_window.child_window(title="Getting started PDF", control_type="ListItem").wait(wait_for='visible') # start explorer in the current path dir_path = path.join(path.dirname(path.realpath(__file__)), 'UIA_Drive') explorer = Application().start('explorer.exe ' + dir_path) Desktop(backend='uia').window(title='UIA_Drive', active_only=True).wait('visible', timeout=10) dlg = Application(backend='uia').connect(path='explorer.exe', title='UIA_Drive')
tab_drive = 'My Drive - Google Drive (Incognito)' # # start google chrome chrome = Application(backend='uia') chrome.start(chrome_dir + ' --force-renderer-accessibility --incognito --start-maximized ' 'https://accounts.google.com/ServiceLogin?service=wise&passive=1209600&continue=https:' '//drive.google.com/?urp%3Dhttps://www.google.ru/_/chrome/newtab?espv%253D2%2526ie%253DUT%23&followup=' 'https://drive.google.com/?urp%3Dhttps://www.google.ru/_/chrome/newtab?espv%253D2%2526ie%253DUT' '<mpl=drive&emr=1#identifier') # wait while a page is loading chrome[tab_log_in].child_window(title_re='Reload.*', control_type='Button').wait('visible', timeout=10) ch_window = chrome[tab_drive].child_window(title="Google Chrome", control_type="Custom") # log in chrome.window().type_keys('TestPywinauto{ENTER}') # username chrome[tab_log_in].child_window(title="Google Chrome", control_type="Custom").\ child_window(title="Back", control_type="Image").wait(wait_for='visible', timeout=10) chrome.window().type_keys('testpywinauto123{ENTER}') # password ch_window.child_window(title="Getting started PDF", control_type="ListItem").wait(wait_for='visible') # start explorer in the current path dir_path = path.join(path.dirname(path.realpath(__file__)), 'UIA_Drive') explorer = Application().start('explorer.exe ' + dir_path) Desktop(backend='uia').window(title='UIA_Drive', active_only=True).wait('visible', timeout=10) dlg = Application(backend='uia').connect(path='explorer.exe', title='UIA_Drive') # find file file = dlg.UIA_Drive.ItemsView.wrapper_object().get_item('test.zip')