def test_site(self): # change this value to the desired username user = "******" # change this value to the desired password for the above user name pwd = "instructor1a" driver = self.driver driver.maximize_window() driver.get("http://sharmila.pythonanywhere.com/") elem = driver.find_element_by_xpath( "/html/body/nav/div/div[2]/ul[2]/li/a").click() time.sleep(2) elem = driver.find_element_by_id("id_username") elem.send_keys(user) time.sleep(2) elem = driver.find_element_by_id("id_password") elem.send_keys(pwd) time.sleep(2) elem.send_keys(Keys.RETURN) assert "Logged In" driver.get("http://sharmila.pythonanywhere.com/") time.sleep(3) elem = driver.find_element_by_xpath( "/html/body/div/div/div/div[2]/div/div/div/div/div[3]/div/div/p[2]/a" ).click() time.sleep(3) elem = driver.find_element_by_xpath( "/html/body/div/div/div/div[3]/table/tbody/tr[2]/td[8]/a").click() time.sleep(3) alert = driver.switch_to.alert alert.accept() driver.get("http://sharmila.pythonanywhere.com/product_list") time.sleep(3) assert "Service deleted"
def is_alert_present(self): try: # self.driver.switch_to_alert() alert = self.driver.switch_to.alert alert.accept() except NoAlertPresentException as e: return False return True
def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to.alert alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True
def baixar_anexos(self, i, list_name_urls, list_file_name, els, t, acp_pra_status, list_file_path, prc_id, n_event, js): # BAIXA OS ANEXOS E CRIA ACOMPANHAMENTO ASSOCIANDO OS ANEXOS CONTIDOS NELES xpath_aux_docs = '//*[@id="TabelaArquivos"]/tbody/tr[{}]/'.format(i + 1) # PEGA A LINHA QUE TA OS DOWNLOAD xpath_aux_docs += 'td/ul/li' wait = WebDriverWait(self.browser, 10) try: wait.until( EC.presence_of_element_located((By.XPATH, xpath_aux_docs))) except: pass ul_files = self.browser.find_elements_by_xpath(xpath_aux_docs) if len(ul_files) > 0: ul_files[0].location_once_scrolled_into_view ul_files = self.browser.find_elements_by_xpath(xpath_aux_docs) j = 0 for li in ul_files: j += 1 direct = 0 n_files = len(os.listdir(self.path_download_prov)) # COLETA ARQUIVO PARA DOWLOAD li_els = li.find_elements_by_xpath('div[2]/div[1]/a') # SALVA OS ARQUIVOS if len(els) == 0: self.browser.execute_script(js[1]) sleep(1) self.browser.execute_script(js[1]) li_els = li.find_elements_by_xpath('div[2]/div[1]/a') # CAPTURA OS DOCUMENTOS doc_els = li.find_elements_by_xpath('div[1]/span') # VERIFICA SE TEM DOC PRA PEGAR if len(doc_els) > 0: # VERIFICA SE O DOWNLOAD TA BLOQUEADO if 'Bloqueado' in doc_els[0].text: continue # PEGA O TITULO DO ARQUIVO title = li_els[0].get_attribute('title').lower() # VERIFICA SE TEM PDF PARA DOWNLOAD pdf = li.find_elements_by_xpath('div[4]/div/a') if '.wav' in title: arq = open('ProcessoContemAudio.txt', 'r') string = arq.read() arq.close() arq = open('ProcessoContemAudio.txt', 'w') string += '\n' n_process = self.browser.find_element_by_xpath( '/html/body/div[2]/form/div[1]/fieldset/span[1]').text string += n_process arq.write(string) arq.close() if not self.check_file_session(): print("erro o check_file_session") return False if '.mp3' in title or len(pdf) == 0: if '.html' in title: li_els[0].click() arq = title.split('.html') direct = 1 self.donwloadAcompanhamento(arq[0]) else: # document.createElement('div'); self.browser.execute_script( 'arguments[0].setAttribute("download", "");', li_els[0]) li_els[0].click() else: pdf[0].click() try: alert = self.browser.switchTo().alert() alert.accept() except: pass t += 1 try: wait = WebDriverWait(self.browser, 2) wait.until(EC.number_of_windows_to_be(2)) wait = WebDriverWait(self.browser, 20) wait.until(EC.number_of_windows_to_be(1)) except TimeoutException: if len(self.browser.window_handles) > 1: self.browser.switch_to_window( self.browser.window_handles[1]) time.sleep(4) erro = self.browser.find_elements_by_class_name( 'texto_erro') if len(erro) > 0 and 'Sem Permis' in erro[0].text: self.browser.close() self.browser.switch_to_window( self.browser.window_handles[0]) return False tipe_err_down = -1 err_down = self.wait_download(n_files) if not direct else 0 acp_pra_status = acp_pra_status and (not err_down) xpath_dowload_arquivo = xpath_aux_docs + '[{}]/div[2]/div[1]/a' xpath_dowload_arquivo = xpath_dowload_arquivo.format(j) wait = WebDriverWait(self.browser, 10) wait.until( EC.element_to_be_clickable((By.XPATH, xpath_dowload_arquivo))) desc_file = self.browser.find_element_by_xpath( xpath_dowload_arquivo).text nome = Tools.convert_base(str(datetime.now())) if not err_down: for arq in os.listdir(self.path_download_prov): if arq not in list_file_path: list_file_path.append(arq) file_downloaded = arq break list_name_urls.append((nome, file_downloaded)) ext = file_downloaded.split('.')[-1].lower() nome = nome + '.' + ext print('.', end='') else: print(':', end='') print('title:' + title) print('erro download') erro = err_down if tipe_err_down is None else False list_file_name.append( ProcessoArquivoModel(pra_prc_id=prc_id, pra_nome=nome, pra_descricao=desc_file, pra_erro=erro)) # VERIFICA SE A SESSÃO FOI ENCERRADA if len(self.browser.window_handles) > 1: self.browser.switch_to_window(self.browser.window_handles[1]) self.browser.close() self.browser.switch_to_window(self.browser.window_handles[0]) acp_pra_status = False print(']', end='') return True
import os import time from selenium import webdriver #driver = webdriver.Chrome() #driver.get("http://www.baidu.com") #time.sleep(5) #driver.implicitly_wait(10) #driver.find_element_by_link_text("hao123").click() #time.sleep(5) from selenium.webdriver.common import alert driver = webdriver.Chrome() #在浏览器打开文件 file_path = 'file:///' + os.path.abspath( "C:\\Users\\打野晓姐姐\\Desktop\\selenium2html\\alert.html") driver.get(file_path) driver.find_element_by_id("tooltip").click() time.sleep(3) alert = driver.switch_to.alert alert.accept() time.sleep(3) driver.quit()
def fetch(self,URI): time.sleep(2) if self.geckodriver: driver = webdriver.Firefox(options = self.options, executable_path = self.geckodriver, service_log_path='./geckodriver.log') filename = HTMLUtil.getFileFromURL(url=URI) driver_process = psutil.Process(driver.service.process.pid) try: writepath = "{}/{}.png".format(self.saveDir, filename) if self.overWrite or not os.path.isfile(writepath): driver.set_page_load_timeout(self.timeout) driver.set_window_size(self.width, self.height) driver.get(URI) driver.save_screenshot(writepath) driver.quit() else: print("Not writing") except UnexpectedAlertPresentException as ueae: #Funky javascript alert handling... alert = Alert(driver) try: alert.accept() #Alert(driver).accept() driver.save_screenshot(writepath) driver.quit() except NoAlertPresentException as nape: if self.debug: logging.debug(nape) driver.save_screenshot(writepath) driver.quit() pass #if self.verbose: # print ("Screen Capture Error! - Page displayed a Javascript alert box") if self.debug: print (ueae) except WebDriverException as wde: if self.debug: logging.debug(wde) if driver_process.is_running(): if self.verbose: print ("Driver is running") firefox_process = driver_process.children() if firefox_process: firefox_process = firefox_process[0] if firefox_process.is_running(): if self.verbose: print("Firefox is still running - killing the driver..") driver.quit() else: if self.verbose: print("Firefox is unresponsive, can't quit - killing the process...") firefox_process.kill() else: if self.verbose: print("Driver error...") except Exception as ex: if self.verbose: print ("Screen Capture Error!") if self.debug: print (ex)
#! python3 from selenium import webdriver from selenium.webdriver.common.keys import Keys import selenium.webdriver.common.alert browser = webdriver.Firefox() # Open Firefox browser.get('http://192.168.1.100/') # Navigate page to power strip login userElem = browser.find_element_by_name('Username') passwdElem = browser.find_element_by_name('Password') userElem.send_keys('COSGC') passwdElem.send_keys('GndSt@tion') passwdElem.send_keys(Keys.ENTER) offElem = browser.find_element_by_link_text('All Outlets OFF') offElem.click() alert = browser.switch_to_alert() alert.accept() browser.close()