zoukankan      html  css  js  c++  java
  • Selenium的三种等待方式(显示等待WebDriverWait()、隐式等待implicitly_wait()、强制等待sleep())

    我们在实际使用selenium或者appium时,等待下个等待定位的元素出现,特别是web端加载的过程,都需要用到等待,而等待方式的设置是保证脚本稳定有效运行的一个非常重要的手段,在selenium中(appium通用)常用的等待分为显示等待WebDriverWait()、隐式等待implicitly_wait()、强制等待sleep()三种

    • sleep(): 强制等待,设置固定休眠时间。 python 的 time 包提供了休眠方法 sleep() , 导入 time 包后就可以使用 sleep(),进行脚本的执行过程进行休眠。
    • implicitly_wait():隐式等待,也叫智能等待,是 webdirver 提供的一个超时等待。等待一个元素被发现,或一个命令完成。如果超出了设置时间的则抛出异常。
    • WebDriverWait():显示等待,同样也是 webdirver 提供的方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异常。默认检测频率为0.5s,默认抛出异常为:NoSuchElementException

    WebDriverWait() 显示等待,语法格式如下:

    WebDriverWait(self,driver,timeout,poll_frequency=POLL_FREQUENCY,ignored_exceptions=None).until(self,method,message=)
     
    WebDriverWait(self,driver,timeout,poll_frequency=POLL_FREQUENCY,ignored_exceptions=None).until_not(self,method,message=)

    WebDriverWait 只有两种方法until与until_not

    until(method,message=") 当某元素出现或什么条件成立则继续执行

    until_not(method,message=")当某元素消失或什么条件不成立则继续执行

    WebDriverWait参数:
    self -- 函数本身,在实际使用的时候不需要输入
    driver -- webdriver的驱动程序,如(IE、FireFox、chrome、safari等)
    timeout -- 超时时间,默认以秒为单位
    poll_frequency -- 轮询频率,休眠时间(步长)的间隔,默认为0.5秒,即检测元素是否存在的频率
    ignored_exceptions -- 超时后的异常信息,默认情况下抛 “NoSuchElementException",大家可以定义忽略的异常信息

    实例

    from selenium import webdriver
    from selenium.common.exception import NoSuchElementException
    from selenium.webdriver.support.ui import WebDriverWait
    dr = webdriver.Chrome()
    dr.get('http://www.baidu.com')
    WebDriverWait(dr,10,1,NoSuchElementException).until(
        lambda dr: dr.find_element_by_id("kw"),message='没有此元素,定义超时!!')
    # WebDriverWait(dr,10)的意思是10秒内每隔0.5秒扫描1次页面变化,直到出现指定的元素后结束,否则抛出异常
  • 相关阅读:
    PAT (Advanced Level) Practice 1055 The World's Richest (25 分) (结构体排序)
    PAT (Advanced Level) Practice 1036 Boys vs Girls (25 分)
    PAT (Advanced Level) Practice 1028 List Sorting (25 分) (自定义排序)
    PAT (Advanced Level) Practice 1035 Password (20 分)
    PAT (Advanced Level) Practice 1019 General Palindromic Number (20 分) (进制转换,回文数)
    PAT (Advanced Level) Practice 1120 Friend Numbers (20 分) (set)
    从零开始吧
    Python GUI编程(TKinter)(简易计算器)
    PAT 基础编程题目集 6-7 统计某类完全平方数 (20 分)
    PAT (Advanced Level) Practice 1152 Google Recruitment (20 分)
  • 原文地址:https://www.cnblogs.com/x00479/p/14244170.html
Copyright © 2011-2022 走看看