显示等待
WebDriverWait 类由 WebDriver 提供的等待方法。在设置时间内,默认每个
一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异
常
-
代码:
WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None)
-
参数解析:
Driver 浏览器驱动
Timeout最长超时时间,默认以秒为单位
poll_frequency 检测的间隔时间,默认为 0.5 秒
ignored_exceptions 超 时 后 的 异 常 信 息 , 默 认 情 况 下 抛 出NoSuchElementException 异常
WebDriverWait 一般由 until()和 until_not()方法配合使用
until(method,message=’’) 调用该方法提供的驱动程序作为一个参数,知道返回值为 Ture
until_not(method,message=’’ 调用该方法提供的驱动程序作为一个参数,知道返回值为False -
导包
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.find_element_by_css_selector('#kw').send_keys('selenium')
sleep(3)
# 显示等待--判断搜索按钮是否存在
element = WebDriverWait(driver, 5,
0.5).until(EC.presence_of_element_located((By.ID, 'su')))
element.click()
隐式等待
- implicitly_wait() 默认参数的单位为秒
#隐式等待时间设定 30 秒
driver.implicitly_wait(30)
强行休眠sleep
sleep()方法有 Python 的 time 模块提供。
在脚本调试过程中,希望脚本再执行到某一位置时做固定时间的休眠,则可以使用。
sleep()默认参数以秒为单位,如果设置时长小于 1 秒,则用小数表示。