个人技术分享

1.前言

在使用selenium时很多元素在使用的时候都需要加载,如果不等待加载结束直接使用就会报错,功能不能继续。一般解决的办法就是使用等待操作。

2.在selenium中常见的等待操作一般有3个

  • sleep
  • implicitly_wait
  • WebDriverWait

sleep 强制等待
强制等待,设置等待多长时间,就要等待多长时间,等待完成后,才会继续下一步。

implicitly_wait
智能等待(隐性等待),直接设置,在等待时间中,元素存在就执行。

driver = webdriver.Chrome()
driver.implicity_wait(30)
……

WebDriverWait
元素存在,但不一定能使用,需要满足其他条件以后才执行

from selenium.webdriver.support.wait import WebDriverWait
wait = WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_eceptions)
ele = wait.until(ES.visibility_of_element_located(EC,visibility_of_element_located((By.Id,'id_value')
……

参数
driver 浏览器驱动
timeout 等待时间
poll_frequency 轮询间隔时间
ignored_eceptions 异常信息

presence_of_element_located是等待元素加载到dom树中的方法,属于expected_conditions类。expected_conditions还提供了很多的条件判断方法:

方法 说明
title_is 判断当前页面的 title 是否等于预期字符串,返回布尔值
title_contains 判断当前页面的 title 是否包含预期字符串,返回布尔值
presence_of_element_located 判断元素是否被加到了 dom 树里(注意,加载到dom树中,并不代表这个元素可见)
visibility_of_element_located 判断元素是否可见
visibility_of 同visibility_of_element_located方法,只是visibility_of_element_located方法参数为locator,这个方法参数是定位后的元素
presence_of_all_elements_located 判断是否至少有 1 个元素存在于 dom 树中。举例:如果页面上有 n 个元素的 class 都是’wp’,那么只要有 1 个元素存在,这个方法就返回 True
text_to_be_present_in_element 判断某个元素中的 text 是否 包含 了预期的字符串
text_to_be_present_in_element_value 判断某个元素中的 value 属性是否包含 了预期的字符串
frame_to_be_available_and_switch_to_it 判断该 frame 是否可以 switch进去,如果可以的话,返回 True 并且 switch 进去,否则返回 False
invisibility_of_element_located 判断某个元素中是否不存在于dom树或不可见
element_to_be_clickable 判断某个元素中是否可见并且可点击
staleness_of 等某个元素从 dom 树中移除,返回 True 或 False
element_to_be_selected 判断某个元素是否被选中了,一般用在下拉列表
element_selection_state_to_be 判断某个元素的选中状态是否符合预期
element_located_selection_state_to_be 跟上面的方法作用一样,只是上面的方法传入定位到的 element,而这个方法传入 locator
alert_is_present 判断页面上是否存在 alert