退出等待时间,次要是思考到网页加载须要工夫,可能因为网速慢,或者应用了 ajax 技术实现了异步加载等,如果程序找不到指定的页面元素,就会导致报错产生。

罕用的有3种期待形式:

  1. 强制期待
  2. 隐式期待
  3. 显示期待

强制期待

应用 Python 本身的库 time.sleep() 能够实现强制期待。

强制期待应用简略,然而,当网络条件良好的时候,倡议缩小应用,因为如果频繁应用强制期待的形式期待元素加载,会导致整个我的项目的自动化工夫缩短。

这种期待形式的应用场景次要是脚本调试

隐式期待

隐式期待实际上是,设置了一个最长的等待时间,如果在这段时间内可能定位到指标,则执行下一步操作,否则会统一等到规定工夫完结,而后再执行下一步。

隐式期待设置一次,对整个 driver 周期都可能起作用,所以,在最开始设置一次即可

留神:在同一个 driver 周期中遇到强制期待,可能会导致隐式期待生效
# 隐式期待,京东的“新人福利”from selenium import webdriverfrom time import sleepdriver = webdriver.Chrome()  # 关上浏览器driver.maximize_window()  # 浏览器最大化driver.get("https://www.jd.com/")  # 跳转至京东driver.implicitly_wait(10)  # 隐式期待 10selement = driver.find_element_by_xpath("//*[@class='user_profit_lk']")  # 定位元素element.click()  # 点击sleep(3)driver.quit()  # 敞开浏览器

显式期待

WebDriverWait 是 Selenium 提供的显式期待的模块,应用原理是:在指定的工夫范畴内,期待到合乎/不合乎某个条件为止。

导入形式:

from selenium.webdriver.support.wait import WebDriverWait

WebDriverWait 参数:

序号参数形容
1driver传入的 WebDriverWait 实例
2timeout超时工夫,期待的最长工夫
3poll_frequency调用 until 或 until_not 中的办法的间隔时间(默认是0.5秒)
4ignored_exceptions疏忽的异样

WebDriverWait 模块含有两个办法:

  1. until
  2. until_not

until 与 until_not 的参数:

序号参数形容
1method在期待期间,每隔一段时间调用这个传入的办法,直到返回值不为 False
2message如果超时,抛出 TimeoutException,将 message 传入异样

通常状况下,WebDriverWait 模块会与 expected_conditions 模块搭配应用,用来写入 until 与 until_not 中的参数——method。

expected_conditions 模块有以下期待条件:

序号期待条件办法形容
1title_is(object)判断题目,是否呈现
2title_contains(object)判断题目,是否蕴含某些字符
3presence_of_element_located(object)--罕用判断某个元素,是否被加到了 dom 树里,并不代表该元素肯定可见
4visibility_of_element_located(object)--罕用判断某个元素,是否被加到了 dom 树里,并且可见,宽和高都大于0
5visibility_of(object)判断元素是否可见,如果可见则返回这个元素
6presence_of_all_elements_located(object)判断是否至多有1个元素存在 dom 树中
7visibility_of_any_elements_located(object)判断是否至多有1个元素在页面中可见
8text_to_be_present_in_element(object)判断指定的元素中是否蕴含了预期的字符串
9text_to_be_present_in_element_value(object)判断指定元素的属性值是否蕴含了预期的字符串
10frame_to_be_available_and_switch_to_it(object)判断该 frame 是否能够 切换进去
11invisibility_of_element_located(object)判断某个元素是否存在与 dom 树中或不可见
12element_to_be_clickable(object)判断某个元素中是否可见,并且是可点击的
13staleness_of(object)期待某个元素从 dom 树中删除
14element_to_be_selected(object)判断某个元素是否被选中,个别用在下拉列表中
15element_selection_state_to_be(object)判断某个元素的选中状态是否合乎预期
16element_located_selection_state_to_be(object)判断某个元素的选中状态是否合乎预期
17alert_is_present(object)判断页面上是否呈现 alert 弹窗
# 模仿场景:点击京东首页的“新人福利”from selenium import webdriverfrom time import sleepfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Chrome()  # 关上浏览器driver.maximize_window()  # 浏览器最大化driver.get("https://www.jd.com/")  # 跳转至京东element = WebDriverWait(driver, 20, 0.5).until(    EC.visibility_of_element_located((By.XPATH, "//*[@class='user_profit_lk']")))  # 20秒内,直到元素在页面中可定位element.click()  # 点击sleep(3)driver.quit()

显式期待,尽管应用起来,相比其余期待形式,显得要简单,然而它的劣势在于灵便,通过封装后,通过简略的调用,就能够使用到自动化测试项目中。

总结