def test_candel_task(self, title): ''' 取消删除任务成功_验证单选第一条进行删除;CRM-ST-BG-003 :return: ''' # username = "******" # password = "******" # tasktitle="任务二" #登录 # lp = LoginPage(self.driver) # lp.open() # lp.login(username,password) # #去任务页面 # ip = IndexPage(self.driver) # ip.task_button_click() # #查找指定任务进行删除 sleep(3) tp = TaskPage(self.driver, TASK_URL) tp.open() tp.task_title_click(title) sleep(3) tp.task_delate_button_click() sleep(3) #删除弹框确认 confirm = Alert(self.driver) confirm.dismiss() sleep(3) #断言 text = tp.task_title_get() logger.info(text) self.assertIn(title, text)
def test_candel_notice(self): ''' 取消删除公告管理;CRM-ST-BG-021 :return: ''' # 登录 username = "******" password = "******" noticetitle = "公告" lp = LoginPage(self.driver) lp.open() lp.login(username, password) # 去到公告管理页面 sleep(3) ip = IndexPage(self.driver) ip.username_click() sleep(3) ip.notice_click() sleep(3) # 删除公告 np = NoticePage(self.driver) np.notice_del(noticetitle) np.notice_del_button_click() # 确认删除 sleep(3) confirm = Alert(self.driver) confirm.dismiss() # 断言 text = np.notice_title_get() logger.info(text) self.asserttIn(noticetitle, text)
def doLogin(self, credential): if self.driver: alert = Alert(self.driver) if alert and credential: print(alert) #alert.send_keys(f'u{Keys.TAB}p') #alert.send_keys( usr + Keys.TAB + pwd ) alert.send_keys(str(credential)) sleep(5) alert.accept() sleep(10) print(self.driver.current_url) if self.driver.current_url == MAIN_URL: self.loged = True print("Loged IN ! :)") return True else: alert.dismiss() print("Could not log in.. :(") return False else: print("Could not auth alert") return False else: print("Could not find driver FF") return False
def _event_after_step(self, context, step): from selenium.webdriver.common.alert import Alert from selenium.common.exceptions import UnexpectedAlertPresentException, \ NoAlertPresentException # any alert must close now, or else the browser will be stuck # in an unusable state for further actions try: if isinstance(step.exception, UnexpectedAlertPresentException): alert = Alert(context.browser) self._log.warning("Browser had alert: %s", step.exception.alert_text or alert.text) alert.dismiss() except NoAlertPresentException: # A bit weird. May happen if alert was not on current `context.browser` pass except Exception: self._log.debug("could not post-process browser alert:", exc_info=True) if step.status == Status.failed: try: msg_url = "Browser currently at: %s\n" % context.browser.current_url except Exception: msg_url = '' self._log.warning("Step: \"%s\" failed.\n%s%s", step.name, msg_url, step.exception or "no exception") self.events.after_step_failed(context, step) try: self.process_logs(context) except urllib3.exceptions.RequestError as e: self._log.warning("Could not fetch logs, browser closed?\n%s", e) except Exception as e: self._log.error("Could not fetch step logs: %s", e)
def wrapper(self, *args, **kwargs): def to_logger(msg, js_level): level = None if js_level == "INFO": level = self.config.javascript.info elif js_level == "WARNING": level = self.config.javascript.warning elif js_level == "SEVERE": level = self.config.javascript.severe if level == "debug": logger.debug(msg) elif level == "info": logger.info(msg) elif level == "warning": logger.warning(msg) elif level == "error": logger.error(msg) elif level == "critical": logger.critical(msg) alert_text = None try: return func(self, *args, **kwargs) except UnexpectedAlertPresentException: # Some websites create an alert to communicate an error message instead of throwing the normal exception # or instead of things normal people use popups for. # However, selenium can be "too quick" to dismiss the alerts and crash. alert = Alert(self.driver) try: alert_text = alert.text alert.dismiss() except NoAlertPresentException: pass except JavascriptException as e: logger.error( "Exception thrown in the browser's Javascript engine.") logger.debug(e) finally: log_records = [] try: log_records = self.driver.get_log("browser") except (WebDriverException, WindowClosedError): logger.warning("Failed to fetch log records from the driver") # Print browser logs for record in sorted(log_records, key=lambda x: int(x["timestamp"])): record["timestamp"] = datetime.fromtimestamp( record["timestamp"] / 1000).strftime("%H:%M") log_line = f"[{record['level']}] {record['message']}" log_level = record["level"] to_logger(log_line, log_level) # Then alert text, if there was any if alert_text is not None: logger.error(f" JS Alert text: {alert_text}") return None
def dismiss_alert(step): """ Dismiss the alert """ try: alert = Alert(world.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass
def dismiss_alert(test): """ Dismiss the alert """ try: alert = Alert(test.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass
def alertDismiss(self, xpath, value): try: alert = Alert(self.driver) alert.dismiss() result = {"state": True, "info": ""} except Exception as e: result = { "state": False, "info": getErrInfo(xpath, "alertDismiss", value, str(e)) } return result
def dismiss_alert(self): """ Dismiss the alert. """ try: alert = Alert(world.browser) alert.dismiss() except WebDriverException: # PhantomJS is kinda poor pass
def _handle_alert(self, alert: Alert_, action: str) -> str: """处理警告框并返回警告框文本内容""" action = action.upper() text = alert.text if action == self.ACCEPT: self.logger.info("接受警告框") alert.accept() elif action == self.DISMISS: self.logger.info("取消警告框") alert.dismiss() elif action != self.LEAVE: raise ValueError(f"无效的警告框处理行为:{action}") return text
def crwalDetail(self, element): try: name = element.find_element_by_tag_name('a').text if not self.exceptMember(name): return member_guild_info = element.find_element_by_class_name( 'gd_fr_info').text.split(' ') grade = member_guild_info[1] contribution = member_guild_info[4] self._sub_driver.get( element.find_element_by_tag_name('a').get_attribute('href')) temp = self._sub_driver.find_element_by_class_name( 'char_info').find_elements_by_tag_name('dl') level = temp[0].find_element_by_tag_name('dd').text.split('LV.')[1] member_class = temp[1].find_element_by_tag_name('dd').text.split( '/')[0] job = temp[1].find_element_by_tag_name('dd').text.split('/')[1] t = self._sub_driver.find_elements_by_css_selector( '#wrap > div.center_wrap > div.char_info_top > div.char_info > div.level_data > span' ) exp = t[0].text.split('경험치')[1].replace(',', '') pop = t[1].text.split('인기도')[1].replace(',', '') member = list() member.append(grade) member.append(name) member.append(level) member.append(member_class) member.append(job) member.append(exp) member.append(contribution) member.append(pop) member.append(self.exemptMember(name)) self._member.append(member) except UnexpectedAlertPresentException as e: print(e) am = Alert(self._sub_driver) am_text = am.text am.dismiss() if am_text == re_text: self.crwalDetail(element) print('RE') else: logger.logging(e, am_text) print(am_text) return True
def alert_dismiss(self): """弹出框的取消""" try: ele = self.alert_is_pressent() ele.dismiss() except: try: alert = self.driver.switch_to_alert() alert.dismiss() except: try: alert = Alert(self.driver) alert.dismiss() except: raise ("not find alert")
class AlertTest(unittest.TestCase): def setUp(self): #Initialize webdriver self.driver = webdriver.Chrome() self.driver.get('http://127.0.0.1:5500/test_stub.html') self.alert = Alert(self.driver) # def test_accept_alert(self): # self.driver.find_element_by_css_selector('button').click() # time.sleep(2) # self.alert.accept() def test_reject_alert(self): self.driver.find_element_by_css_selector('button').click() time.sleep(2) self.alert.dismiss() def tearDown(self): self.driver.close()
def alert_action(self, alert_action_state, text=None): try: alert = Alert(self.context.driver) if alert_action_state == AlertAction.ACCEPT: alert.accept() self.context.logger.info("Alert accept performed") return True elif alert_action_state == AlertAction.DISMISS: alert.dismiss() return True elif alert_action_state == AlertAction.SETTEXT: print(text) alert.send_keys(text) return True elif alert_action_state == AlertAction.GETTEXT: return alert.text return False except NoAlertPresentException as e: raise NoAlertPresentException(e)
def test_alerts(self): """This is used to test different types of alerts""" self.driver.find_element(By.ID,"alertBox").click() ac = Alert(self.driver) ac.accept() time.sleep(1) self.driver.find_element(By.ID,"confirmBox").click() ac = Alert(self.driver) ac.accept() time.sleep(1) self.driver.find_element(By.ID, "confirmBox").click() ac = Alert(self.driver) ac.dismiss() time.sleep(1) self.driver.find_element(By.ID,"promptBox").click() ac = Alert(self.driver) ac.text ='chrome' time.sleep(2) ac.accept()
def wrapper(*args, **kwargs): self = args[0] alert_text = None try: return func(*args, **kwargs) except UnexpectedAlertPresentException: # Some websites create an alert to communicate an error message instead of throwing the normal exception # or instead of things normal people use popups for. # However, selenium can be "too quick" to dismiss the alerts and crash. alert = Alert(self.driver) try: alert_text = alert.text alert.dismiss() except NoAlertPresentException: pass except JavascriptException as e: logger.error( "Exception thrown in the browser's Javascript engine.") logger.debug(e) finally: log_records = [] try: log_records = self.driver.get_log("browser") except (WebDriverException, WindowClosedError): logger.warning("Failed to fetch log records from the driver") # Print browser logs for record in sorted(log_records, key=lambda x: int(x["timestamp"])): record["timestamp"] = datetime.fromtimestamp( record["timestamp"] / 1000).strftime("%H:%M") log_line = "[{level}] {message}".format(**record) if record["level"] in JS_DEBUG_LEVELS: logger.debug(log_line) elif record["level"] in JS_ERROR_LEVELS: logger.error(log_line) # Then alert text, if there was any if alert_text is not None: logger.error(f" JS Alert text: {alert_text}")
def mute_mic_and_cam(): print("Muting mic and camera...") try: # close popup dismiss = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "/html/body/div/div[3]/div/div[2]/div[3]/div/span/span"))) dismiss.click() # dismiss alert alert = Alert(driver) alert.dismiss() # mute mic mic = WebDriverWait(driver, 10).until( EC.element_to_be_clickable(( By.XPATH, "/html/body/div[1]/c-wiz/div/div/div[7]/div[3]/div/div/div[2]/div/div[1]/div[" "1]/div/div[4]/div[1]/div/div/div"))) mic.click() print("Muted mic and camera") except Exception as e: print(e)
class Common_driver(): # de def __init__(self, webElement_for_select=None): self.act = webdriver.ActionChains(Driver().driver()) self.alt = Alert(Driver.driver()) # self.select = Select(webElement_for_select) def explicit_wait(self, xpath): # self.wait = WebDriverWait(Driver().driver(), 10).until(EC.presence_of_element_located((xpath))) pass # return self.wait # use ActionChains class for clicking through action def actions_click(self, menu): # self.act.move_to_element(menu) self.act.move_to_element(menu).click().perform() # self.act.click(menu) # self.act.perform() def actions_double_click(self, menu): self.act.double_click(menu).perform() def actions_move_to_element(self, menu, hidden_menu): self.act.move_to_element(menu).click().perform() self.act.click(hidden_menu).perform() # self.act.perform() #ActionChains for click and hold def click_and_hold(self, webElement1): # act = ActionChains(Driver().driver()) self.act.click_and_hold(webElement1).perform() #context click def context_click(self, webElement1): self.act.context_click(webElement1).perform() #drag and drop def drag_and_drop(self, webElement1_drag, webElement1_drop): self.act.drag_and_drop(webElement1_drag, webElement1_drop).perform() # key down def key_down(self, value): self.act.key_down(Keys.CONTROL).send_keys(value).key_up( Keys.CONTROL).perform() #suppose you want to write ctrl+c , then put 'c' in value #Alerts - use this class to interact with alert prompts . It contains methods # for dismissing ,accepting, and getting text from alert prompts # accepting #accept the accept available def alert_accept(self): self.alt.accept() # confirm a alert dialog def alert_dismiss(self): self.alt.dismiss(self) # authenticate the username and password def alert_authenticate(self, username, password): Driver().driver().swith_to_alert.authenticate(username, password) def alert_send_keys(self, keys_to_send): self.alt.send_keys(keys_to_send) #text - to get text from alert # here is end of the alert @classmethod def sele(cls, webElement1): sel = Select(webElement1) return cls(sel) # select starts def select_by_index(self, webElement1, index): self.sel = Select(webElement1) # self.sel = Common_driver.sele(webElement1) self.sel.select_by_index(index) def select_by_visible_text(self, webElement1, text): self.sel = Select(webElement1) self.sel.select_by_visible_text(text) def select_by_value(self, webElement1): self.sel = Select(webElement1) self.sel.select_by_value(value)
def handlePopUp(): alert = Alert(driver) alert.dismiss() # sometimes NoAlertPersentException occurs
def alert_operate(self, accept=True): alert = Alert(self.driver) print(alert.text) alert.accept() if accept else alert.dismiss()
def dismiss_alert(browser): try: alert = Alert(browser) alert.dismiss() except WebDriverException: pass
def dismiss_alert(browser): try: alert = Alert(browser) alert.dismiss() except WebDriverException: pass
driver = webdriver.Chrome() driver.get("file:///C:/Users/ARUNM/Desktop/Alert1.html") driver.maximize_window() # This is simple alert popup elem1 = driver.find_element_by_xpath("//*[@id='content']/p[4]/button") elem1.click() alt_elem1 = Alert(driver) assert "A simple Alert" in alt_elem1.text alt_elem1.accept() # This alert discmiss ction elem2 = driver.find_element_by_xpath("//*[@id='content']/p[8]/button") elem2.click() alt_elem2 = Alert(driver) assert "Confirm pop up with OK and Cancel button" in alt_elem2.text alt_elem2.dismiss() elem3 = driver.find_element_by_xpath("//*[@id='content']/p[11]/button") elem3.click() alt_elem3 = Alert(driver) # print(alt_elem3.text) assert "Do you like toolsqa?" in alt_elem3.text sleep(4) alt_elem3.dismiss() driver.quit() # assert "Google" in driver.page_source # print("Assert pass") # driver.close()
#Trocar para Alerta Alerta alert = browser.switch_to.alert alert.accept() ## Avançado de Alert try: WebDriverWait(browser, 3).until(EC.alert_is_present(), 'Timed out waiting for PA creation ' + 'confirmation popup to appear.') alert = browser.switch_to.alert alert.accept() print("alert accepted") except TimeoutException: print("no alert") #Operando com Alert alert = Alert(driver) # Instancia a classe alert alert.dismiss() # Clica no Botão Cancelar alert.accept() # Confirma o alerta alert.text # Pega o texto presente na caixa de Alerta alert.send_keys("Texto a ser enviado para o Alert") # Login com Alert driver.switch_to.alert.authenticate('usuario', "senha") Alert(driver).accept() #Trocar de Iframe driver.switch_to.frame("frame3") #Nome do Iframe driver.switch_to.default_content() #Volta ao Frame Padrão driver.switch_to.frame(2) #Selecionando o Frame por Número driver.switch_to.frame(driver.find_element_by_tag_name("iframe")[1]); #Selecionando Iframe por busca de "Find"
from selenium.webdriver import Firefox from selenium.webdriver.common.alert import Alert browser = Firefox() browser.get('http://selenium.dunossauro.live/aula_11_a') browser.find_element_by_id('alert').click() alerta = Alert(browser) # Liadar com erros alerta = browser.switch_to.alert # Não lida com erros alerta.accept() # Confirma, clica no OK alerta.dismiss() # Confirma, clica no OK
def dismiss(self): alert = Alert(self.driver) alert.dismiss()
from selenium import webdriver from selenium.webdriver.common.alert import Alert from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support.expected_conditions import alert_is_present from selenium.webdriver.support.select import Select browser = webdriver.Chrome() browser.get("https://www.techstepacademy.com/training-ground") # Click an Alert alert = Alert(browser) # Gets Text from the alert alert.text # Accept or Dismiss an Alert alert.accept() alert.dismiss() # Wait, until something has happened WebDriverWait(browser, 10).until(alert_is_present()) # This is an explicit wait print("An Alert Appeared") # Selection Box sel = browser.find_element_by_id('sel1') my_select = Select(sel) # Options my_select.options # Select by visible Text my_select.select_by_visible_text('Beets')
seat_number_input = driver.find_element_by_id( "ctl00_ContentPlaceHolder1_txtSeatno") mothers_name_input = driver.find_element_by_id( "ctl00_ContentPlaceHolder1_txtMother") submit_btn = driver.find_element_by_id( "ctl00_ContentPlaceHolder1_btnSubmit") seat_number_input.clear() mothers_name_input.clear() mothers_name_input.send_keys(MOTHER_NAME) seat_number_input.send_keys(i) submit_btn.click() a = Alert(driver) a.dismiss() except Exception as e: sleep(5) print("Result Found") print(f"Seat Number: {i}") print( driver.find_element_by_xpath( "/html/body/form/div[5]/div[2]/span/div/table[1]/tbody/tr[2]/td[1]" ).text) print( driver.find_element_by_xpath( "/html/body/form/div[5]/div[2]/span/div/table[3]/tbody/tr[28]/td[1]" ).text.strip()) finally:
print('해당 주차 강의를 다운로드 합니다. 완료될 때까지 기다려주세요.') print('- 온라인 출석부에서 해당 동영상 강의 열람 횟수가 1회 증가합니다.') vod_list = week.find_all('li', {'class': 'activity vod modtype_vod'}) for i in range(0, len(vod_list)): vodLink = re.search(r'https://.*\d*', str(vod_list[i])).group() vodLink = vodLink[:vodLink.find('"')] vodLink = vodLink.replace('view', 'viewer') if (vodLink.find( 'https://plato.pusan.ac.kr/mod/vod/viewer.php?') == -1 ): continue driver.get(vodLink) try: da = Alert(driver) da.dismiss() except: print("", end='') html = driver.page_source soup = BS4(html, 'html.parser') source = str(soup.find_all('source')) source = source[source.find('https'):source.find('m3u8') + 4] fileDownload( courseName + week.attrs['aria-label'] + '_' + str(i + 1), source) driver.get('https://plato.pusan.ac.kr/') driver.find_element_by_xpath( '//*[@id="page-header"]/div[1]/div[2]/ul/li[2]/a').click() driver.quit() exit()
def dismissAlert(driver): alt = Alert(driver) print(alt.text) alt.dismiss()
from selenium.webdriver import Firefox from selenium.webdriver.common.alert import Alert browser = Firefox() browser.get('http://selenium.dunossauro.live/aula_11_a') browser.find_element_by_id('prompt').click() alerta = Alert(browser) alerta.accept() alerta.dismiss()
select=Select(selectLang) optionList=select.options select.select_by_index(1) select.select_by_value=('python') select.select_by_visible_text('PYTHON') option=select.first_selected_option print(option.get_attribute('value')) wd.find_element_by_id('alert').click() alt=wd.switch_to.alert alt.accept() #wd.find_element_by_id('alert').click() wd.execute_script('alert("ok")') alt=Alert(wd) alt.dismiss() script=''' var callback=arguments[arguments.length-1]; window.setTimeout(function(){callback('timeout')},3000); ''' result=wd.execute_async_script(script) print(result) try: #wd.find_element_by_id('alert').click() result=WebDriverWait(wd,5).until(expected_conditions.alert_is_present(),"Timed out waiting for alert") print(result) alt=Alert(wd) print(alt.text)