def _handle_captcha2(self, url): cur_host = urlparse(self._get_webdriver().current_url).hostname for cookie in self._session.cookies: # Only set cookies matching the current domain, cf. https://github.com/w3c/webdriver/issues/1238 if cur_host is cookie.domain.lstrip('.'): self._get_webdriver().add_cookie({ 'name': cookie.name, 'value': cookie.value, 'path': cookie.path, 'domain': cookie.domain, }) self._get_webdriver().get(url) log_interval = 10 cur = 0 timeout = 60 * 60 * 24 * 7 # 1 week while cur < timeout: try: cur = cur + log_interval # Update before exceptions can happen WebDriverWait(self._get_webdriver(), log_interval).until_not( lambda drv: self._webdriver_has_captcha()) break except TimeoutException: self.logger.info( f"Solving the captcha took already {cur} seconds (of maximum {timeout} s)." ) except UnexpectedAlertPresentException as e: # This can apparently happen when reCAPTCHA has hiccups: # "Cannot contact reCAPTCHA. Check your connection and try again." self.logger.info( f"Unexpected alert while waiting for captcha completion: {e.args}" ) time.sleep(15) except DOSException as e: self.logger.info(f"Google thinks we are DOSing the captcha.") raise e except (WebDriverException) as e: self.logger.info( f"Browser seems to be disfunctional - closed by user?") raise e except Exception as e: # TODO: This exception handler should eventually be removed when # we know the "typical" (non-error) exceptions that can occur. self.logger.info( f"Unhandled {type(e).__name__} while waiting for captcha completion: {e.args}" ) else: raise TimeoutException( f"Could not solve captcha in time (within {timeout} s).") self.logger.info(f"Solved captcha in less than {cur} seconds.") for cookie in self._get_webdriver().get_cookies(): cookie.pop("httpOnly", None) cookie.pop("expiry", None) self._session.cookies.set(**cookie) return self._session
def patiently_find(self, look_for, by=By.ID, timeout=10): """Find an element, only timing out after `timeout` seconds. `look_for` is the element identifier, and `by` is the type of search to perform. """ try: result = WebDriverWait(self.selenium, timeout).until( expected_conditions.presence_of_element_located( (by, look_for))) except TimeoutException: raise TimeoutException( 'Timed out looking for "{look_for}" by {by}.'.format( look_for=look_for, by=by)) return result
def get_element_by_text(self, text): """ Retrieves a visible element that contains input text. :param text: Text to look for :raise: selenium.webdriver.support.wait.TimeoutException: The element was not found before the timeout_period. :return: appium.webdriver.webelement.WebElement """ wait = WebDriverWait(self.driver, self.timeout_period) try: return wait.until( EC.presence_of_element_located( (MobileBy.ANDROID_UIAUTOMATOR, 'new UiSelector().textContains("%s")' % text))) except TimeoutException: raise TimeoutException(u'Couldn\'t find the text "%s" ' u'before the timeout of %s seconds' % (text, self.timeout_period))
def get_element_by_id(self, resource_id): """ Retrieves a visible element that matches given ID. :param resource_id: ID to look for. It should be the raw id and does not need the app package name to be included. IE: demo_link_button :raise: selenium.webdriver.support.wait.TimeoutException: The element was not found before the timeout_period. :return: appium.webdriver.webelement.WebElement """ wait = WebDriverWait(self.driver, self.timeout_period) try: return wait.until( EC.presence_of_element_located( (MobileBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("%s:id/%s")' % (self.app_package, resource_id)))) except TimeoutException: raise TimeoutException(u'Couldn\'t find the id "%s" before the ' u'timeout of %s seconds' % (resource_id, self.timeout_period))
def _until_predicate(self, method: FromWebDriver[T], predicate: ty.Callable[[T], bool], message: str = '') -> T: """Calls the method provided with the driver as an argument until the \ return value not satisfied predicate.""" screen = None stacktrace = None while True: poll_timer = _Timer(self._min_poll_duration, autostart=True) try: value = method(self._driver) if predicate(value): return value except self._ignored_exceptions as exc: if predicate(None): return True # it's True just in order to copy WebDriverWait behavior screen = getattr(exc, 'screen', None) stacktrace = getattr(exc, 'stacktrace', None) sleep(poll_timer.timeout()) if self._timer.timeout() == 0: break raise TimeoutException(message, screen, stacktrace)
def wait_to_load(self): started_load_at = time() while self.execute_script("return document.readyState") != "complete": if started_load_at > self.default_delay: raise TimeoutException(msg="Wait time exced")