使用selenium做自动化测试时,通常情况下需要找到页面元素才可以进行下一步,而使用webdriver控制浏览器运行相对反应都很慢,如果不等待页面加载,大多数情况下webdriver是找不到元素进行操作的,所以需要进行等待元素可见或可操作。
有三种方式进行等待:
-
强制等待
import time time.sleep(3) #等待3秒
固定休眠时间,单位为秒,导入
time
包使用,不智能,等待太多,运行时间长。 -
隐式等待
driver.implicitly_wait(10) #隐式等待10秒
webdriver提供的方法,初始化driver后使用即可,以后在driver的整个生命周期中都有效。这是一个全局的等待,等待页面加载完成。即:每次在定位元素时,都会等待页面全部元素加载完成才进行下一步,也是会影响运行速度的。
-
显式等待
使用WebDriverWait()类结合until()或者until_not()方法使用:
#导入模块 from selenium.webdriver.support.wait import WebDriverWait #调用该方法提供的驱动程序作为一个参数,直到返回值为True WebDriverWait(driver,10,1).until(method,message="") #调用该方法提供的驱动程序作为一个参数,直到返回值为False WebDriverWait(driver,10,1).until_not(method,message="")
在设置的时间(10s)内,等待后面的条件发生。如果超过设置时间未发生,则抛出异常。在等待期间,每隔一定时间(1s)(默认0.5秒),调用until或until_not里的方法,直到它返回True或False。
这里的method参数不是任意方法都可以调用,必须有
__call__
方法,否则抛异常'xxx' object is not callable
。我们可以使用WebElement的
is_displayed()
、is_enabled()
、is_selected()
方法,也可以使用selenium提供的expected_conditions
模块中的各种条件,也可以自己封装。is_displayed()
使用示例:def find_element_f(self,*loc): ''' 显示等待:实现方式1:WebDriverWait + until 通过find_element的is_displayed()等方法判断 :param loc:参数传入定位元组 :return: element对象 ''' try: WebDriverWait(driver,10).until(lambda the_driver: the_driver.find_element(*loc).is_displayed()) return self.driver.find_element(*loc) except: print("未找到元素")
WebDriverWait与expected_conditions结合使用
expected_conditions模块提供了很多的判断页面元素各种状态的类以及方法
示例:
def find_element_e(self,*loc): ''' 显示等待:实现方式2:WebDriverWait + until结合expected_conditions模块的判断方法实现 :param loc:参数传入带*的定位元组 :return:element对象 ''' try: el=WebDriverWait(driver,10).until(EC.visibility_of_element_located(loc)) return el except: print("未找到元素")
[created_at:2020-06-26]
[我的导航目录]