def waitForContent(self, content, timeCount=20): result = None count = 0 while True: try: result = self.driver except NoSuchElementException, e: pass if result: log_info("Load Finish.") break waitSeconds(3) count = count + 1 if count > timeCount: raise TimeoutException("wait for load Finish time out.") log_info("Not load Finish, wait " + str(3 * count) + " seconds. check id :" + content)
def waitTextChanged(self, css: str, oldText: str) -> str: sign = 1 for x in range(30): e = self.elem(css) try: newText = e.text if newText != oldText: return newText except StaleElementReferenceException: pass self._driver.execute_script('window.scrollBy(0,%d);' % (5 * sign)) print('window.scrollBy(0,%d); sleep(2);' % (5 * sign)) sign = -sign sleep(2) raise TimeoutException('[waitTextChanged] oldText="%s", ' 'newText="%s"' % (oldText, newText))
def wait_for_elem_text_to_be_valid(self, css_selector, validator, timeout=2): try: self._wait_for_method_to_return( self.get_elem_text, timeout, css_selector, True, custom_return_validator=validator, ) except TimeoutException: raise TimeoutException( f'The element text "{css_selector}" doesn\'t turn to be valid after {timeout}s' )
def wait_for(func, timeout=5, timeout_msg=None): """ Calls the method provided with the driver as an argument until the return value is not False. Throws an error if the WebDriverWait timeout clock expires. Otherwise this method will return None. """ msg = timeout_msg or "Timed out after {} seconds.".format(timeout) try: WebDriverWait( driver=world.browser.driver, timeout=timeout, ignored_exceptions=(StaleElementReferenceException) ).until(func) except TimeoutException: raise TimeoutException(msg)
def retryA(statement, timeOut: float = 6.2, pollFreq: float = 0.3): timeElap = 0 while timeElap < timeOut: timeBegin = time.time() try: return statement() except (StaleElementReferenceException, NoSuchElementException, StopIteration): pass except Exception as ex: ulog('raise %s %s' % (type(ex), str(ex))) raise ex #ulog('sleep %f secs'%pollFreq) time.sleep(pollFreq) timeElap += (time.time() - timeBegin) raise TimeoutException(getFuncName() + ': timeOut=%f' % timeOut)
def wait_for_primefaces(self, timeout=None, message=None): if timeout: timeoutSecs = timestr_to_secs(timeout) else: timeoutSecs = self.timeout errmsg = message or ('Timed out waiting for PrimeFaces queue ' + 'to empty after specified timeout.') try: WebDriverWait(self._selib.driver, timeoutSecs, 0.2)\ .until(lambda x: self._selib.driver.execute_script(js_wait_for_primefaces)) except TimeoutException: if self.error_on_timeout: raise TimeoutException(errmsg)
def wait_for_clickable(css_selector, timeout=30): """ Waiting for the element to be present and clickable. Throws an error if the WebDriverWait timeout clock expires. Otherwise this method will return None. """ # Sometimes the element is clickable then gets obscured. # In this case, pause so that it is not reported clickable too early try: WebDriverWait( driver=world.browser.driver, timeout=timeout, ignored_exceptions=(StaleElementReferenceException) ).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_selector,))) except TimeoutException: raise TimeoutException("Timed out waiting for {} to be clickable.".format(css_selector))
def find(self, locator, tag=None, first_only=True, required=True, parent=None): timeout = self.timeout if self.enable_implicit_wait: try: WebDriverWait(self._selib.driver, timeout, 0.2)\ .until(lambda x: self._selib.driver.execute_script(js_wait_for_primefaces)) except TimeoutException: if self.error_on_timeout: raise TimeoutException('Timed out waiting for ' + 'PrimeFaces queue to empty ' + 'after specified timeout.') elements = ElementFinder.find(self, locator, tag, first_only, required, parent) return elements
def panel_waiting_with_timeout(context, panel_id, action, seconds): """ Function that waits for panel to appear but for a maximum amount of time """ if action == 'appear': css_selector = '#%s:not([class*="ui-collapsible-collapsed"])' % panel_id elif action == 'disappear': css_selector = '#%s[class*="ui-collapsible-collapsed"]' % panel_id else: raise ValueError("Action can be either appear or disappear. Duh!") try: WebDriverWait(context.browser, int(seconds)).until( EC.presence_of_element_located((By.CSS_SELECTOR, css_selector))) except TimeoutException: raise TimeoutException("Panel %s did not %s after %s seconds" % (panel_id, action, seconds))
def esperar_carga_total_de_archivo(webdriver: WebDriver, tiempo_de_espera: int = 720): tiempo_de_inicio = Temporizador.obtener_tiempo_timer() tiempo_transcurrido = 0 se_cargo_correctamente_el_fichero = False while tiempo_transcurrido < tiempo_de_espera: tiempo_transcurrido = Temporizador.obtener_tiempo_timer( ) - tiempo_de_inicio modal_de_exito = webdriver.find_elements_by_xpath( '//div[@class="up-file-actions isDone"]') if len(modal_de_exito) == 1: se_cargo_correctamente_el_fichero = True break span_texto_subida_de_archivo = webdriver.find_elements_by_xpath( '//span[text()="Se ha cancelado la carga"]') if len(span_texto_subida_de_archivo) > 0: lista_mensajes_error_carga_archivo = webdriver.find_elements_by_xpath( '//span[@class="ng-tns-c3-0"][text()="Error en la carga"]') if len(lista_mensajes_error_carga_archivo) > 0: div_botones_actions = webdriver.find_elements_by_class_name( 'up-file-actions') if len(div_botones_actions) > 0: lista_botones_action = div_botones_actions[ 0].find_elements_by_tag_name('app-svg-icon') if len(lista_botones_action) > 0: boton_reintentar_carga_archivo = lista_botones_action[ 0] try: boton_reintentar_carga_archivo.click() except ElementClickInterceptedException: pass if se_cargo_correctamente_el_fichero: UtilsEvaluaciones.esperar_desaparicion_modal_exito(webdriver) else: raise TimeoutException( msg= 'Han transcurrido mas de 12 minutos, sin cargar correctamente el archivo ' 'dentro del portal de Claro Drive')
def selenium_get(url): i = 0 while i < retries: try: driver.get(url) time.sleep(5) print('----------------------the page was loaded in time -------------') except TimeoutException: i = i + 1 print("Time out, Retrying..........(%(i)s/%(max)s)" % {'i': i, 'max': retries}) continue else: return True msg = "Page was anot loaded in time" raise TimeoutException(msg)
def find(self, *locator, timeout=None): """ 定位元素 :param locator: 元素定位器 :param timeout: 超时时间 :return: 元素对象 """ try: return self._init_wait(timeout).until( EC.visibility_of_element_located(locator=locator) ) except NoSuchElementException: self._driver.close() raise NoSuchElementException(msg='元素定位失败,定位方式为:{}'.format(locator)) except TimeoutException: self._driver.close() raise TimeoutException(msg='元素定位失败,定位方式为:{}'.format(locator))
def wait_activity(self, activity, timeout, interval=1): """Wait for an activity: block until target activity presents or time out. Android only. - _activity_ - target activity - _timeout_ - max wait time, in seconds - _interval_ - sleep interval between retries, in seconds """ if not activity.startswith('.'): activity = ".%s" % activity driver = self._current_application() if not driver.wait_activity(activity=activity, timeout=float(timeout), interval=float(interval)): raise TimeoutException(msg="Activity %s never presented, current activity: %s" % (activity, self.get_activity()))
def waiting_for_clickability(element, timeout): _poll = 1 end_time = time.time() + timeout while True: try: element.click() return True except: pass time.sleep(_poll) if time.time() > end_time: break raise TimeoutException()
def step(self, screen_name): """ For a given Zeplin screen, the method open the version side-bar, scrapes the content (with filtering) and stores the scraped content in a JSON file named according to the @screen_name and prefixed with the group the screen belongs to. :param screen_name: The names of the screen prefixed by the group it belong to. :return: Nothing. """ screencontent = self.driver.find_element_by_xpath( '//div[@class="screenContent"]') # Now we must open the version sidebar screenviewcontainer = screencontent.find_element_by_class_name( "screenViewContainer") screenview_widgets = screenviewcontainer.find_element_by_class_name( "widgets") toggle_button = screenview_widgets.find_element_by_xpath( '//button[contains(@class, "versionsToggleWidget")]') toggle_button.send_keys(Keys.RETURN) # Wait a "fixed" amount try: WebDriverWait(self.driver, self.DELAY).until( EC.presence_of_element_located( (By.CLASS_NAME, 'versionHeader'))) # Should also get the name of the screen except TimeoutException: raise TimeoutException('Loading page took too much time') versions_sidebar = screencontent.find_element_by_class_name( "versionsSidebar") versions = versions_sidebar.find_element_by_class_name("versions") version_elements = versions.find_elements_by_class_name( "versionHeader") self.driver.implicitly_wait(self.DELAY) version_list = [] for elem in version_elements: version_date = elem.find_element_by_class_name( 'versionHeaderText').text version_list.append(version_date) # Flush results to disk with open(os.path.join(self.SCREEN_DIRECTORY, screen_name + ".json"), 'w', encoding='utf-8') as writer: writer.write(json.dumps(version_list))
def until_not(self, method, message=''): """ Calls the method provided with the driver as an argument until the \ return value is False. """ end_time = time.time() + self._timeout while True: try: value = method(self._driver) if not value: return value except self._ignored_exceptions: return True time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message)
def wait_for_element_by_name(driver, element_name): # Poll for 5 secs until element is found timeout = 5000 poll_frequency = 0.2 end_time = time.time() + timeout while True: try: return driver.find_element_by_name(element_name) except NoSuchElementException: pass except WebDriverException: pass time.sleep(poll_frequency) if time.time() > end_time: break raise TimeoutException( 'Element named: {} could not be found'.format(element_name))
def has_attribute_value(self, attribute, value, timeout=TIMEOUT): """Wait until an element is found which has the specified attribute and value. Args: attribute (str): the attribute name value (str): the value that must be present timeout (int): max time to wait """ self.verify() try: self.wait_until(lambda _: self._try( lambda _: value == self.web_element.get_attribute(attribute)), timeout=timeout) except TimeoutException: raise TimeoutException(u"{}Timeout waiting for element attr '{}' " "to be '{}'".format(self._log_prefix(), attribute, value))
def until(self, method, message=''): if self._timeout != 0: end_time = time.time() + self._timeout while True: try: value = method(self._driver) if value: return value except: pass time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(""" failed while waiting %s seconds with step %s second to assert not %s%s """ % (self._timeout, self._poll, method.__class__.__name__, message))
def wait_for_response(self, path, timeout=10): start = time.time() while time.time() - start < timeout: request = self._client.find(path) if request is not None: finished = time.time() req = Request(request, self._client) obj = {"time": finished - start, "body": req.response.body} return obj else: time.sleep(0.2) raise TimeoutException( 'Timed out after {}s waiting for response {}'.format( timeout, path))
def verify_msg_time(self,type ,loca, total_time): start_time = int(time()) end_time = int(time()) + total_time #print(end_time) i = 1 while True: if self.find_elements(type,loca).is_enabled() ==True: print("验证码等待时间为" + str(i + 1) + "s") else: i=i+1 sleep(1) start_time = int(time()) #print(start_time) if start_time > end_time: raise TimeoutException("超时时间为" + str(i + 1) + "s") break continue
def until_not(self, method, message=''): """Calls the method provided with the driver as an argument until the return value is False.""" end_time = time.time() + self._timeout while (True): try: value = method(self._driver) if not value: return value except NoSuchElementException: return True except StaleElementReferenceException: pass time.sleep(self._poll) if (time.time() > end_time): break raise TimeoutException(message)
def until(self, method, message=''): screen = None stacktrace = None end_time = time.time() + self._timeout while True: try: value = method(self._webelement) if value: return value except self._ignored_exceptions as exc: screen = getattr(exc, 'screen', None) stacktrace = getattr(exc, 'stacktrace', None) time.sleep(0.5) if time.time() > end_time: break raise TimeoutException(message, screen, stacktrace)
def _wait_with_screenshot(webdriver, entity, condition, timeout=None, polling=None): if timeout is None: timeout = config.timeout if polling is None: polling = config.poll_during_waits try: return wait_for(entity, condition, timeout, polling) except TimeoutException as e: screenshot = helpers.take_screenshot(webdriver, ) msg = '''{original_msg} screenshot: {screenshot}'''.format(original_msg=e.msg, screenshot=screenshot) raise TimeoutException(msg, e.screen, e.stacktrace)
def wait_until_onscreen(self, selector): """ Wait until the element matching the provided selector has been moved into the viewable page """ end_time = time.time() + settings.SELENIUM_TIMEOUT while True: try: element = self.sel.find_element_by_css_selector(selector) location = element.location if location["x"] >= 0 and location["y"] >= 0: self.screenshot() return True except (NoSuchElementException, StaleElementReferenceException): pass time.sleep(settings.SELENIUM_POLL_FREQUENCY) if time.time() > end_time: break raise TimeoutException("'%s' should be offscreen" % selector)
def wait_for_page_load(self, timeout=DefaultTimeouts.DEFAULT_TIMEOUT, throw_on_timeout=False): """ Waits for the current document to load (although AJAX and other loads might still be happening) :param timeout: Time to wait for document to load, seconds :param throw_on_timeout: Boolean to throw exception when timeout is reached """ try: WebDriverWait(self.webdriver, timeout).\ until(lambda driver: driver.execute_script( 'return document.readyState') == 'complete') except TimeoutException: if throw_on_timeout: raise TimeoutException( "Page elements never fully loaded after %s seconds" % timeout)
def popup_waiting_with_timeout(context, popup_id, action, seconds): """ Function that wait for keyadd-popup to appear but for a maximum amount of time """ if action == 'appear': css_selector = '#%s[class*="ui-popup-active"]' % popup_id elif action == 'disappear': css_selector = '#%s[class*="ui-popup-hidden"]' % popup_id else: raise ValueError("Action can be either appear or disappear. Duh!") try: WebDriverWait(context.browser, int(seconds)).until( EC.presence_of_element_located((By.CSS_SELECTOR, css_selector))) except TimeoutException: raise TimeoutException("Popup %s did not %s after %s seconds" % (popup_id, action, seconds))
def wait_until_option_disabled(self, selector, option_text): """ Wait until the specified select option is disabled; the entire select widget may be replaced in the process """ end_time = time.time() + settings.SELENIUM_TIMEOUT while True: try: select = Select( self.sel.find_element_by_css_selector(selector)) for option in select.options: if option.text == option_text and not option.is_enabled(): return option except (NoSuchElementException, StaleElementReferenceException): pass time.sleep(settings.SELENIUM_POLL_FREQUENCY) if time.time() > end_time: break raise TimeoutException("Select option should have been disabled")
def init_webdriver(self): t = time.time() try: print("Start to connect webdriver") self.driver = webdriver.Remote('http://localhost:5555/wd/hub', DesiredCapabilities.FIREFOX) self.handler_driver_time = time.time() - t _ = self.driver.implicitly_wait(self.time_out) except TimeoutException: raise TimeoutException("TimeoutException") else: print("Get driver successful! {}".format(self.handler_driver_time)) self.driver.set_window_size(1280, 1024) dest = "https://www.klook.com" self.action = Action(self.driver, dest)
def wait_while(self, function, intervals_in_seconds=10, max_times=10): matches = False times = 0 while times < max_times and not matches: end_time = time.time() + intervals_in_seconds while True: time.sleep(1) matches = function(self) if not matches or time.time() > end_time: break times += 1 if not matches: raise TimeoutException( "Timeout when executing the given function." " Intervals in seconds: {0}. Tried: {1} times".format( intervals_in_seconds, max_times))