*隐式等待
driver.implicitly_wait(time_to_wait)
当查找节点而节点并没有立即出现的时候,隐形等待一段时间直到元素被找到或命令完成,该命令在每个会话中仅需执行一次
In [5]: driver = webdriver.Chrome() DevTools listening on ws://127.0.0.1:12823/devtools/browser/5e6b75be-748f-42e0-a726-02883e6ff2ef In [6]: ?driver.implicitly_wait Signature: driver.implicitly_wait(time_to_wait) Docstring: Sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout. :Args: - time_to_wait: Amount of time to wait (in seconds) :Usage: driver.implicitly_wait(30)
*显示等待
先指定好某个要查找的节点,然后指定一个最长的等待时间,默认每0.5秒轮询一次,如果在规定时间内加载出来了这个节点,那就返回查找的节点,如果到了规定时间依然没有加载出该节点,则会抛出超时异常。
且在调用期间默认忽略NoSuchElementException异常,注解如下:
In [7]: from selenium.webdriver.support.ui import WebDriverWait In [8]: ?WebDriverWait Init signature: WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None) Docstring: <no docstring> Init docstring: 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()) File: d:\anaconda3\lib\site-packages\selenium\webdriver\support\wait.py Type: type
例:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver = webdriver.Chrome(chrome_options=option) wait = WebDriverWait(driver, 5) datarange = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="managed-accounts-view"]/div/div[1]/div/date-range-selector/div/div[1]/*'))) #节点可点击 datarange.click()