最近在使用selenium2Library時,用到其中的 Wait Until Page函數,因咱們的網頁相對比較敏感,常常獲取不到,不明覺歷web
看看源碼吧,以下:app
def wait_until_page_contains_element(self, locator, timeout=None, error=None): """Waits until element specified with `locator` appears on current page. Fails if `timeout` expires before the element appears. See `introduction` for more information about `timeout` and its default value. `error` can be used to override the default error message. See also `Wait Until Page Contains`, `Wait For Condition`, `Wait Until Element Is Visible` and BuiltIn keyword `Wait Until Keyword Succeeds`. """ if not error: error = "Element '%s' did not appear in <TIMEOUT>" % locator self._wait_until(timeout, error, self._is_element_present, locator)
核心的等待函數在這裏ide
def _wait_until_no_error(self, timeout, wait_func, *args): timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs maxtime = time.time() + timeout while True: timeout_error = wait_func(*args) if not timeout_error: return if time.time() > maxtime: raise AssertionError(timeout_error) time.sleep(0.2)
。。。。函數
函數中,寫死等待0.2秒,尚未參數能夠改。太暴力。ui
再來看看selenium原生的webdriverWait是怎麼寫的spa
def until(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value is not False.""" screen = None stacktrace = None end_time = time.time() + self._timeout while True: try: value = method(self._driver) if value: return value except self._ignored_exceptions as exc: screen = getattr(exc, 'screen', None) stacktrace = getattr(exc, 'stacktrace', None) time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message, screen, stacktrace)
從源碼中能夠看出,等待時間能夠自定義,except除了元素不可見,也還能夠加自定義的錯誤。比selenium2library更好用code