1.利用help
函数得到WebDriverWait
中的方法。
from selenium.webdriver.support.wait import WebDriverWait
print(help(WebDriverWait))
class WebDriverWait(builtins.object)
| Methods defined here:
|
| __init__(self, driver, timeout, poll_frequency=0.5, ignored_exceptions=None)
| Constructor, takes a WebDriver instance and timeout in seconds.
|
| :Args:
| - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
| - timeout - Number of seconds before timing out
| - poll_frequency - sleep interval between calls
| By default, it is 0.5 second.
| - ignored_exceptions - iterable structure of exception classes ignored during calls.
| By default, it contains NoSuchElementException only.
|
| Example:
| from selenium.webdriver.support.ui import WebDriverWait
|
| element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId"))
|
| is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\
|
| until_not(lambda x: x.find_element_by_id("someId").is_displayed())
|
| __repr__(self)
| Return repr(self).
|
| until(self, method, message='')
| Calls the method provided with the driver as an argument until the return value is not False.
|
| until_not(self, method, message='')
| Calls the method provided with the driver as an argument until the return value is False.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
2.里面的until
方法以及until_not
方法很重要,来看一下方法具体的定义以及使用方法,如下代码中有一句value = method(self._driver)
,这句代码含义是:当每一次until调用方法method的时候都会给method传入(self.__driver)
class WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds.
:Args:
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
- timeout - Number of seconds before timing out
- poll_frequency - sleep interval between calls
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls.
By default, it contains NoSuchElementException only.
Example:
from selenium.webdriver.support.ui import WebDriverWait \n
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
until_not(lambda x: x.find_element_by_id("someId").is_displayed())
"""
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)
def until_not(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is False."""
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if not value:
return value
except self._ignored_exceptions:
return True
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message)
3.我在实际操作中遇到了一个问题就是until里面的method传参的问题。下面的第一段代码是正确的,第二段代码是错误的。第一段代码中的lamada表达式就是until要调用的method,当until调用这个method的时候就会给lamada表达式中的x赋值为self.__driver,所以第二段代码中的写法是错误的
element = WebDriverWait(driver, 10).until(lambda x:x.find_element_by_id("someId"))
element = WebDriverWait(driver, 10).until(driver.find_element_by_id("someId"))
4.until还可以传EC.presence_of_element_located
对象作为参数。这个时候可能会有同学疑惑,刚刚不是还说until
是传入一个method
作为参数吗。现在怎么又说可以传入一个对象作为参数呢?这里涉及一个python中的基础问题。就是如果一个类实现了call方法,那么他的对象就可以像函数一样表示。就可以把它的对象当成函数。下面具体解释一下。还是先打印出刚刚所说的EC.EC.presence_of_element_located
类的具体方法,可以看到这个类确实有__call__
方法。 __call__(self, driver)
,Call self as a function
.就是说可以把这个类的实例对象看成是函数,像函数一样使用。
print(help(EC.presence_of_element_located))
class presence_of_element_located(builtins.object)
| An expectation for checking that an element is present on the DOM
| of a page. This does not necessarily mean that the element is visible.
| locator - used to find the element
| returns the WebElement once it is located
|
| Methods defined here:
|
| __call__(self, driver)
| Call self as a function.
|
| __init__(self, locator)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
None
用__init__(self, locator)
创建了一个类的实例EC.presence_of_element_located((By.XPATH, "//a[text()='1']")
,这里的By.XPATH, "//a[text()='1']"
就是传入的loacator
参数。
直接传入这个对象作为until函数的参数就可以了。因为根据__call__
函数的定义,这个对象就可以像函数一样被调用。即
WebDriverWait(driver, 8, 0.5).until(EC.presence_of_element_located((By.XPATH, "//a[text()='1']")))