【说明】
1:等待是为了使脚本执行更加稳定
2:常用的休眠方式:time模块的sleep方法
【selenium模块中的等待方法】
表达式 | 说明 |
---|---|
implicitly_wait() | 设置webdriver等待时间 |
WebDriverWait | 等待条件满足或者超时后退出 from selenium.webdriver.support.ui import WebDriverWait |
【代码】
#设置webdriver等待时间
>>> d=webdriver.Firefox()
>>> d.get('http://www.baidu.com')
>>> d.find_element_by_id('kw').send_keys('麦子学院')
>>> d.implicitly_wait(5)
>>> d.find_element_by_id('kw1')
#等待条件满足或者超时后退出
>>> from selenium.webdriver.support.ui import WebDriverWait
>>> help(WebDriverWait)
Help on class WebDriverWait in module selenium.webdriver.support.wait:
#说明
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)
#部分实例
def get_ele_times(driver, times, func):
return WebDriverWait(driver, times).until(func)
ele_login = get_ele_times(d, 10, lambda d: d.find_element_by_link_text(arg['text_id']))
ele_login.click()