当前位置:首页 > Web开发 > 正文

也还是会再等3秒

2024-03-31 Web开发

我们在使用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’),会返回元素

WebDriverWait显示期待源码分解

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/32375.html