示例代码:
from selenium.webdriver.support.wait import webdriverwait as WD
def find_element(self, by, locator): """ find alone element :param by: eg: id, name, xpath, css..... :param locator: id, name, xpath for str :return: element object """ try: print('[Info:Starting find the element "{}" by "{}"!]'.format(locator, by)) element = WD(self.driver, self.outTime).until(lambda x: x.find_element(by, locator)) # 其实指driver except TimeoutException as t: print('error: found "{}" timeout!'.format(locator), t) else: return element
对于 element = WD(self.driver, self.outTime).until(lambda x: x.find_element(by, locator))如何理解?
它是说程序每隔xx秒看一眼,如果条件成立了,则执行下一步;否则继续等待,直到超过设置的最长时间,然后抛出TimeoutException异常
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)