标签:false span screen python except ESS void __name__ lam
我们在使用selenium 查找元素的时候,为了避免网页加载慢,会加一个sleep(x秒)
这样能解决加载慢的问题,但也存在2个问题
1.如果你设置的等待时间过了,还没加载出来,就会报“NoSuchElementException”
2.如果设置等待5秒,2秒就加载出来了,也还是会再等3秒,这样影响执行效率
有什么好的方法呢?
当然是有的,selenium.webdriver.support.wait下有一个 WebDriverWait类,就能很好的解决上面的问题
具体用法如下
from selenium.webdriver.support.wait import WebDriverWait from selenium import webdriver driver = webdriver.Chrome() elem = WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_id(‘su’)) elem.click()
初始化WebDriverWait,传入driver,最长等待时间5秒
调用util方法,utile接收一个方法
我们来看下源码
import time from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException POLL_FREQUENCY = 0.5 # 没0.5秒调用一下util接收到的方法 IGNORED_EXCEPTIONS = (NoSuchElementException,) # 忽略遇到异常 class WebDriverWait(object): def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None): """
此处省略注释
""" self._driver = driver self._timeout = timeout self._poll = poll_frequency # avoid the divide by zero if self._poll == 0: self._poll = POLL_FREQUENCY exceptions = list(IGNORED_EXCEPTIONS) if ignored_exceptions is not None: try: exceptions.extend(iter(ignored_exceptions)) except TypeError: # ignored_exceptions is not iterable exceptions.append(ignored_exceptions) self._ignored_exceptions = tuple(exceptions) def __repr__(self): return ‘<{0.__module__}.{0.__name__} (session="{1}")>‘.format( type(self), self._driver.session_id) 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)
WebDriverWait构造方法需要接收driver和timeout(超时时间),默认调用频率poll_frequency(0.5秒)
until方法中主要是这一段
value = method(self._driver) if value: return value
执行接收的方法,如果接收方法执行OK,则直接返回入参方法的返回值
即我们传入的driver.find_element_by_id(‘su’),会返回元素
标签:false span screen python except ESS void __name__ lam
原文地址:https://www.cnblogs.com/easy-test/p/12143482.html