def gettime(): # Clear all previous calculate windows prfin = autoit.win_exists("[Title:"+calctitle+"]") while prfin: autoit.control_click("[Title:"+calctitle+"]", "Button1", clicks=2) prfin = autoit.win_exists("[Title:"+calctitle+"]") # Create updated calculate window autoit.control_click("[Title:"+maintitle+"]", "ToolbarWindow321", x=185, y=7) prfin = autoit.win_exists("[Title:"+calctitle+"]") while not prfin: prfin = autoit.win_exists("[Title:"+calctitle+"]") # Read calculate window and get hms data unparsed = autoit.win_get_text("[Title:"+calctitle+"]") while not unparsed: unparsed = autoit.win_get_text("[Title:"+calctitle+"]") regfind = worktime.search(unparsed).group() (h, m, s) = regfind.split(':') # Close calculate window autoit.control_click("[Title:"+calctitle+"]", "Button1", clicks=2) # Return seconds return int(h)*3600 + int(m)*60 + int(s)
def ondownloadpressed(): # Wait for download window to close dlfin = autoit.win_exists("[Title:"+filetitle+"]") while dlfin: dlfin = autoit.win_exists("[Title:"+filetitle+"]") # Get calculated time return gettime()
def is_activated(self): #call system command os.popen("slmgr /dli") self.wait_dialog_box() #determine if it is licensed if autoit.win_exists("Windows Script Host",text="已授权") or autoit.win_exists("Windows Script Host",text="已取得授權") or autoit.win_exists("Windows Script Host",text="Licensed"): self.activation=1 self.close_dialog_box() #return the result return(self.activation)
def clean_dlg(self): try: if autoit.win_exists(self.wid_prompt): autoit.win_activate(self.wid_prompt) autoit.control_click(self.wid_prompt, self.cid_prompt_ok) except autoit.AutoItError: pass
def win_exists(cls, title, **kwargs): """ call autoit.win_exists 检查指定的窗口是否存在. :return 1:窗口存在; 0:窗口不存在. """ return autoit.win_exists(title, **kwargs)
def file_upload(window_name, file_name): autoit.win_wait(window_name, 30) if not autoit.win_exists(window_name): raise Exception("No File Upload Window is found") else: autoit.win_activate(window_name) autoit.control_focus(window_name, "[ID:1148]") autoit.control_set_text(window_name, "[ID:1148]", file_name) autoit.control_click(window_name, "[ID:1]")
def serverShutdown(): ret = False if autoit.win_exists("C:\Windows\system32\cmd.exe"): #Checks if the window Minecraft would be in is currently running print("The Minecraft server was found and will be shut down in 30 seconds.") #Note: The following command brings the Minecraft command prompt to the front. #It will be run after any pause just in case a user activates another screen some point #during that pause. autoit.win_activate("C:\Windows\system32\cmd.exe") autoit.send("say The server will be shutting down in 30 seconds.") autoit.send("{Enter}") for s in range(30,-1,-1): time.sleep(1) if(s == 15 or s == 10 or (s <= 5 and s >= 3)): autoit.win_activate("C:\Windows\system32\cmd.exe") autoit.send("say " + str(s) + " seconds till shutdown{!}") autoit.send("{Enter}") elif(s == 2): autoit.win_activate("C:\Windows\system32\cmd.exe") autoit.send("say " + str(s) + " seconds till shutdown{!}{!}{!}") autoit.send("{Enter}") elif(s == 1): autoit.win_activate("C:\Windows\system32\cmd.exe") autoit.send("say " + str(s) + " SECOND TILL SHUTDOWN{!}{!}{!}{!}{!}") autoit.send("{Enter}") print("Server is shutting down.") autoit.win_activate("C:\Windows\system32\cmd.exe") autoit.send("say Server is shutting down now{!}") autoit.send("{Enter}") autoit.send("stop") autoit.send("{Enter}") #sleep to give the server time to shutdown time.sleep(5) #Log to console whether server is stopped if autoit.win_exists("C:\Windows\system32\cmd.exe") == False: print("The Minecraft server was successfully shutdown!") ret = True else: print("Error: The stop command was sent but the server is still found!") ret = False else: #Minecraft instance was not found print("The server was not found.") ret = True #Return true because this function only needs to make sure the server is off return ret
def login(window_name, username, password): print "Waiting for window with name: " + window_name autoit.win_wait(window_name, 30) if not autoit.win_exists(window_name): raise Exception("No Browser Login Window is found") else: print "Activating window" autoit.win_activate(window_name) sleep(1) print "Sending username & password" autoit.send(username) autoit.send("{tab}") autoit.send(password) autoit.send("{enter}")
def addfile(self, windowname, filename): '''pyautoit实现上传附件''' # autoit.mouse_click(x=630, y=255) sleep(1.5) if autoit.win_exists(windowname): autoit.win_active(windowname) autoit.mouse_click(x=1580, y=46) APPLICATION_PATH = self.Base_dir() + r'/data/uploadfile' autoit.send(APPLICATION_PATH) autoit.send('{ENTER}') autoit.mouse_click(x=780, y=970) autoit.send(filename) autoit.send('!o') sleep(1) else: raise Exception('没有打开文件窗口')
def addfile(): '''上传附件流程''' autoit.mouse_click(x=630, y=255) sleep(3) if autoit.win_exists('打开文件'): autoit.win_active('打开文件') autoit.mouse_click(x=780, y=50) path = os.path.dirname(__file__) npos = 'IMTestScript' APPLICATION_PATH = Base.common_path( path=path, npos=npos) + r'IMTestScript\IM_Test\data\uploadfile' autoit.send(APPLICATION_PATH) autoit.send('{ENTER}') autoit.mouse_click(x=780, y=970) autoit.send('uploadfile_1.txt') autoit.send('!o') sleep(2) else: raise Exception('没有打开文件窗口')
def win_close_all(cls, title, limit_loop_time=0, **kwargs): """ 关闭所有匹配的指定窗口. limit_loop_time 限制循环的次数(0 表示无限制) :return [ close result, ...] close result(1:成功; 0:窗口不存在.) """ wins = [] if isinstance(limit_loop_time, (int, float)): limit_loop_time = int(limit_loop_time) elif isinstance(limit_loop_time, basestring) and common.isNumber(limit_loop_time): try: limit_loop_time = int(limit_loop_time) except ValueError: limit_loop_time = int(float(limit_loop_time)) else: limit_loop_time = 0 current_time = 0 key = "text" while True: current_time = current_time + 1 if key in kwargs.keys(): text = kwargs[key] else: text = "" if autoit.win_exists(title, text=text): result = autoit.win_close(title, **kwargs) wins.append(result) else: break if limit_loop_time != 0 and current_time > limit_loop_time: break return wins
def upload(self,path,date,h,m,ap): try: self.driver.find_elements_by_class_name('rwb8dzxj')[2].click() #create post button time.sleep(1) self.driver.find_elements_by_class_name('rwb8dzxj')[45].click() #instagram feed button time.sleep(2) element=self.driver.find_elements_by_class_name('_4ik4')[9+self.config['pageindex']] #page click self.driver.execute_script("arguments[0].click();",element) #caption element=self.driver.find_elements_by_class_name('_1mf')[0] caption="" if len(self.captions): caption=self.captions[str(random.randint(0,len(self.captions)-1))] clipboard.copy(caption) element.send_keys(Keys.CONTROL, 'v') self.driver.find_elements_by_class_name('_82ht')[0].click() # self.driver.find_element_by_xpath('/html/body/div[6]/div/div/div/div[2]/div[1]/div/div[5]/div/div/div/span').click() #file upload button time.sleep(1) #Selenium only works on browser, 'upload window' is OS window, so i used autoit to control it. _attempt=4 while _attempt: try: self.driver.find_elements_by_class_name('_m')[0].click() time.sleep(1) autoit.win_activate("Open") break except: _attempt-=1 autoit.control_send("Open","Edit1",path) autoit.control_send("Open","Edit1","{ENTER}") time.sleep(1) self.driver.find_elements_by_class_name('_8122')[0].click() self.driver.find_elements_by_class_name('_kx6')[1].click() self.driver.find_elements_by_class_name('_58al')[1].click() self.driver.find_elements_by_class_name('_58al')[1].send_keys(date) #set date #set hour element=self.driver.find_elements_by_class_name('_4nx3')[0] actions=ActionChains(self.driver) actions.move_to_element(element).click().send_keys(h).perform() #set minute element=self.driver.find_elements_by_class_name('_4nx3')[1] actions=ActionChains(self.driver) actions.move_to_element(element).click().send_keys(m).perform() #set AM/PM element=self.driver.find_elements_by_class_name('_4nx3')[2] actions.move_to_element(element).click().send_keys(ap).perform() self.driver.find_elements_by_class_name('_43rm')[1].click() #schedule button time.sleep(5) if os.path.splitext(path)[1]=='.mp4': time.sleep(5) self.attempt=15 except KeyboardInterrupt: main() except Exception as e: print(colors["red"],e,sep="") self.attempt-=1 if autoit.win_exists('Open'): autoit.win_close('Open') if self.attempt: self.driver.get(igurl) time.sleep(3) self.upload(self.getpost(),date,h,m,ap) else: self.err()
def exists(self): ''' :description 检查指定的窗口是否存在. :return 1:窗口存在; 0:窗口不存在. ''' return autoit.win_exists(self.title, text=self.text)
def launch_application(self): if not autoit.win_exists(WINDOW_START): autoit.run(self.config.get('exe', 'tmpgencvmw')) autoit.win_wait_active(WINDOW_START) autoit.win_activate(WINDOW_START)
def exists(self): """检查指定窗口是否存在""" return autoit.win_exists(self.title, text=self.text)
def _dlexists(): for i in xrange(1, 100): if autoit.win_exists("[Title"+downloadtitle.format(i)+"]"): return True return False
def add_terms(self, params): """ `Description:` To add terms `Param:` params: ictionary contains terms information `Returns:` contract_state `Created by:` Kenash K """ try: try: import autoit except ImportError as e: print e.msg verify_text = '' contract_state = False params = defaultdict(lambda: '', params) self.action_ele.input_text("ac_contractNumber", params["contractNumber"]) #self.action_ele.input_text("ac_forecastDate", params["forecastDate"]) if bool(params['forecastDate']): if params['forecastDate'] == "today": cur_date = datetime.date.today() self.action_ele.input_text('ac_forecastDate', cur_date.strftime('%m/%d/%Y')) else: self.action_ele.input_text('ac_forecastDate', params['forecastDate']) self.action_ele.input_text("ac_notes", params["notes"]) self.action_ele.click_element("ac_uploadContract") for i in range(5): #for clicking the browse button since another control overlaps the button ex = self.query_ele._element_finder("ac_uploadFile1") action = webdriver.common.action_chains.ActionChains( self._browser._browser) action.move_to_element_with_offset(ex, 5, 5).click().perform() time.sleep(5) #autoit.win_wait_active("[TITLE:Open]", 5) #status1 = autoit.win_active("[CLASS:#32770]") status1 = autoit.win_exists("[TITLE:Open]") #status1=1 console(status1) if status1 == 0: print("click on browse failed") print("Retrying number: %s " % str(i)) else: #Exiting as Open Dialog box has been found print("Exiting as Open Dialog box has been found") break else: print("Raising Exception") raise time.sleep( 2) #this is for the path to resolve in the browse window autoit.control_send("[TITLE:Open]", "Edit1", params["filePath"]) time.sleep(1) autoit.control_click("[TITLE:Open]", "Button1") #autoit.send(params["filePath"]) #time.sleep(2) #autoit.send("{ENTER}") self.action_ele.explicit_wait("ac_Ok") time.sleep(2) self.action_ele.click_element("ac_Ok") self.action_ele.select_from_dropdown_using_text( "ac_termVersion", params["termVersion"]) self.action_ele.select_from_dropdown_using_text( "ac_termLength", params["termLength"]) self.action_ele.select_from_dropdown_using_text( "ac_termRenewalType", params["termRenewalType"]) self.action_ele.select_from_dropdown_using_text( "ac_termInstall", params["termInstall"]) self.action_ele.click_element("ac_nextbut_3") #self.action_ele.explicit_wait("ac_finish") time.sleep(2) self.action_ele.click_element("ac_finish") self.action_ele.explicit_wait("ac_alert_ok", 120) verify_text = self.query_ele.text_present( "New Contract successfully added") time.sleep(2) self.action_ele.click_element("ac_alert_ok") ##contract_message = self.query_ele.get_text('contract_alert_message') if verify_text: contract_state = True #self.action_ele.explicit_wait("ac_accountContractsDataGridAddContract", 20) #remove exta wait to load grid uncomment if page is very slow return contract_state except Exception, e: print(e) print("Failed to add product for contract") self.action_ele.takeScreenshot( inspect.currentframe().f_code.co_name) return False
def scrape(self): bot = self.bot for v in range(1, 26): bot.get('http://magento-site.net/computer-accessories.html?p=' + str(v)) time.sleep(15) for n in range(1, 21): product = "product" + str(n) pro = "pro" + str(n) product = bot.find_element_by_xpath( '//html/body/div[3]/div/div[2]/div[1]/div/div[1]/div/div[3]/ul/li[' + str(n) + ']/div/a') pro = product.get_attribute('href') # print(pro) bot.get(pro) title = "title" + str(n) title = bot.find_element_by_xpath( '//html/body/div[3]/div/div[2]/div[1]/div/div[1]/div/div[4]/div[1]/form/div[4]/div[1]/h1' ).text print(title) price = "price" + str(n) price = bot.find_element_by_xpath( '//html/body/div[3]/div/div[2]/div[1]/div/div[1]/div/div[4]/div[1]/form/div[4]/div[2]/div[1]/div/span/span' ).text #print(price) pprice = price[1:] ppprice = pprice.replace(',', '') #print(ppprice) sku = 'sku' + str(n) sku = bot.find_element_by_xpath( '/html/body/div[3]/div/div[2]/div[1]/div/div[1]/div/div[4]/div[1]/form/div[4]/div[2]/div[2]/p[1]/span' ).text #print(sku) sdesc = "short-desc" + str(n) sdesc = bot.find_element_by_xpath( '//html/body/div[3]/div/div[2]/div[1]/div/div[1]/div/div[4]/div[1]/form/div[4]/div[4]/div' ).text #print(sdesc) ldesc = "long-desc" + str(n) ldesc = bot.find_element_by_xpath( '//html/body/div[3]/div/div[2]/div[1]/div/div[1]/div/div[4]/div[2]/div[1]/div' ).text #print(ldesc) img = "image" + str(n) img = bot.find_element_by_xpath( '//html/body/div[3]/div/div[2]/div[1]/div/div[1]/div/div[4]/div[1]/form/div[3]/div[1]/div/a/img' ).get_attribute('src') urllib.request.urlretrieve(img, "image{}.png".format(str(n))) if v == 1: bot.execute_script("window.open('');") bot.switch_to.window(bot.window_handles[1]) time.sleep(2) if v == 1: bot.get('magento.site/') time.sleep(5) email = bot.find_element_by_name('login[username]') password = bot.find_element_by_name('login[password]') email.clear() password.clear() email.send_keys(self.username) password.send_keys(self.password) password.send_keys(Keys.RETURN) time.sleep(10) bot.refresh() time.sleep(15) catalog = bot.find_element_by_xpath( "//div[1]/nav/ul/li[2]/a") catalog.click() time.sleep(5) product = bot.find_element_by_xpath( '//div[1]/nav/ul/li[2]/div/ul/li/div/ul/li/a') product.click() time.sleep(10) addproduct = bot.find_element_by_id( "add_new_product-button").click() time.sleep(15) time.sleep(5) bot.find_element_by_name("product[sku]").send_keys(sku) bot.find_element_by_name("product[name]").send_keys(title) bot.find_element_by_name("product[price]").send_keys(ppprice) bot.execute_script("scroll(0, 390);") #categories bot.find_element_by_xpath( '//html/body/div[2]/main/div[2]/div/div/div/div[2]/div[1]/div/fieldset/fieldset[4]/div/div[1]/div[2]/div/div[1]' ).click() bot.find_element_by_xpath( '//html/body/div[2]/main/div[2]/div/div/div/div[2]/div[1]/div/fieldset/fieldset[4]/div/div[1]/div[2]/div/div[2]/ul/li/ul/li[9]/div' ).click() bot.find_element_by_xpath( '//html/body/div[2]/main/div[2]/div/div/div/div[2]/div[1]/div/fieldset/fieldset[4]/div/div[1]/div[2]/div/div[2]/div[2]/button' ).click() # click and upload descriptions bot.find_element_by_xpath( '//html/body/div[2]/main/div[2]/div/div/div/div[2]/div[3]/div[1]' ).click() time.sleep(4) bot.execute_script("scroll(390, 1220);") desc = bot.find_element_by_id('product_form_description_ifr') desc.click() time.sleep(2) desc.send_keys(ldesc) bot.execute_script("scroll(1220, 1620);") time.sleep(2) shortdesc = bot.find_element_by_id( 'product_form_short_description_ifr') shortdesc.click() time.sleep(2) shortdesc.send_keys(sdesc) # bot.find_element_by_xpath('//div/div[2]/div[5]/div[1]').click() # time.sleep(1) # continue from here, bot.execute_script("scroll(1620, 2990);") bot.find_element_by_xpath( '//html/body/div[2]/main/div[2]/div/div/div/div[2]/div[5]/div[1]' ).click() time.sleep(2) bot.find_element_by_xpath( '//html/body/div[2]/main/div[2]/div/div/div/div[2]/div[5]/div[2]/fieldset/div/div[2]/div[1]/div[1]/div[1]' ).click() filepath = "C:\\Users\\Umar\\Desktop\\Code\\magento-bot\\image" + str( n) + ".png" autoit.win_wait_active("File Upload", 6) if autoit.win_exists("File Upload"): autoit.control_send("File Upload", "Edit1", filepath + "{ENTER}") # bot.find_element_by_id('fileupload').send_keys(os.getcwd()+"\image"+str(n)+".png") time.sleep(19) bot.find_element_by_id('save-button').click() time.sleep(30) bot.execute_script("window.history.go(-1)") time.sleep(19) #drv.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png") bot.switch_to.window(bot.window_handles[0]) time.sleep(4) bot.execute_script("window.history.go(-1)") time.sleep(16)