Waits 等待
WebDriver因为是异步触发元素或事件,有些时候脚本可能是间接性的,也有可能是断断续续的;又加浏览器和WebDriver脚本之间的存在竞争条件问题,因此我们需要引入等待包,让脚本运行不会出现阻塞或失败
使用等待时,我们需要引入等待包:
ui和wait里面都有WebDriverWait类,目前两种引包使用都没问题的;区别的话就是:ui模块里面引入的类就是wait下的WebDriverWait类
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.wait import WebDriverWait
三大等待之:显式等待
显式等待部分源码简介:
class WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY,
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 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 TimeoutExcept