• selenium webdriver——设置元素等待


    >>如今大多数Web应用程序使用ajax技术,当浏览器在加载页面时,页面上的元素可能并不是同时被加载完成,这给定位元素的定位增加了困难,

     如果因为在加载某个元素时延迟而造成ElementNotVisibleException(不可见元素异常)的情况出现,那么就会降低自动化脚本的稳定性,设置

     元素等待可改善这种问题造成的不稳定。

     >>WebDriver提供了两种类型的等待:

      >>显示等待:

       具体格式如下:

     1 #Author:xiaoxiao
     2 from selenium import webdriver
     3 from selenium.webdriver.common.by import By
     4 from selenium.webdriver.support.ui import WebDriverWait
     5 from selenium.webdriver.support import expected_conditions as ec
     6 
     7 def abc():
     8     #打开浏览器
     9     driver = webdriver.Firefox()
    10     driver.get('http://www.baidu.com')
    11     #显示等待
    12     element = WebDriverWait(driver,5,0.5).until(ec.presence_of_all_elements_located((By.ID,"kw")))
    13     driver.find_element_by_id("kw").send_keys("selenium")
    WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions).until()
    
    driver:浏览器驱动
    timeout:最长超时时间,默认以秒为单位
    poll_frequency:检测的间隔(步长)时间,默认为0.5S
    ignored_exceptions:超时后的异常信息,默认情况下抛NoSuchElementException
    WebDriverWait()一般由until()或until_not()方法配合使用,下面是方法说明
    until(method,message='')
    调用该方法提供的驱动程序作为一个参数,直到返回值为True
    until_not(method,message='')
    调用该方法提供的驱动程序作为一个参数,直到返回值为False
    presence_of_all_elements_located()
    判断元素是否存在
    

      >>隐式等待:

       通过一定的时长等待页面上某元素加载完成,如果超出了设置的时长元素还没有被加载,则抛出NoSuchElementException异常,WebDriver

       提供了implicitly_wait()方法来实现隐式等待,默认设置为0

    1 #Author:xiaoxiao
    2 from selenium import webdriver
    3 
    4 def abc():
    5     #打开浏览器
    6     driver = webdriver.Firefox()
    7     #隐式等待 设置等待时间为10秒
    8     driver.implicitly_wait(10)
    9     driver.get('http://www.baidu.com')

     >>sleep休眠方法

      在脚本执行中固定休眠

     1 #Author:xiaoxiao
     2 from selenium import webdriver
     3 from time import sleep
     4 
     5 def abc():
     6     #打开浏览器
     7     driver = webdriver.Firefox()
     8     driver.get('http://www.baidu.com')
     9     sleep(3)
    10     driver.quit()
  • 相关阅读:
    Fedora install chrome
    Ubuntu13.04 安装 chrome
    cjb
    屏蔽视频广告
    tars环境部署
    rpm包安装失败的解决办法
    Java环境变量配置错误
    Protobuf的安装使用
    fpm打包工具
    gcc6.3的安装
  • 原文地址:https://www.cnblogs.com/airener/p/5951835.html
Copyright © 2020-2023  润新知