zoukankan      html  css  js  c++  java
  • selenium 设置元素等待

    webdriver 有2种等待方式:显式等待和隐式等待

    显式等待

    定义:使webdriver等待某个条件成立时继续执行,否则达到最大时长时抛出异常

    WebdriverWait类是由WebDriver 提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则会抛出异常。

    格式如下:

    WebDriverWait(driver,timeout,poll_frequency = 0.5,ignored_exceptions = None)
    • driver:浏览器驱动
    • timeout:最长超时时间默认以秒为单位
    • poll_frequency:检测的间隔时间,默认为0.5S
    • ignored_exceptions:超时后的异常信息,默认情况下抛出NoSuchElementException异常

    WebDriverWait()一般由until()或until_not()方法配合使用,下面是until()和until_not()方法的说明。

    • until(method,message  = ''+3)

    调用该方法提供的驱动程序为一个参数,知道返回值为False

    在以下示例中,通过as关键字将excepected_conditions重命名为EC,并调用presence_of_element_located()方法判断元素是否存在。

     1 #-*-coding:utf-8 -*-
     2 print("hello,world")
     3 from selenium import webdriver
     4 from selnium.webdriver.common.by import By
     5 from selnium.webdriver.support.ui import webdriverWait
     6 from selenium.webdriver.support import expected_conditions as EC
     7 
     8 driver = webdriver.Firefox()
     9 driver.get('http://www.baidu.com')
    10 
    11 element = webdriverWait(driver,5,0.5).until(
    12                         EC.presence_of_element_located((By.ID,'kw'))
    13                         )
    14 element.send_keys('selenium')
    15 driver.quit()

    隐式等待

    WebDriver提供了implicitly_wait()方法来实现隐式等待,默认设置为0,用法相对简单。

     1 #隐式等待
     2 from selenium import webdriver
     3 from selenium.common.exceptions import NoSuchElementException
     4 from time import ctime
     5 
     6 driver = webdriver.Firefox()
     7 
     8 #设置隐式等待为10s
     9 driver.implicitly_wait(10)
    10 driver.get("http://www.baidu.com")
    11 try:
    12     print(ctime())
    13     driver.find_element_by_id('kw22').send_keys('selenium')
    14 except NoSuchElementException as e:
    15     print(e)
    16 
    17 finally:
    18     print(ctime())
    19     driver.quit()

    implicitly_wait()默认参数的单位为秒,延时等待是在设定好的时间内,不断进行元素定位(轮询),定位到了就继续执行,定位不到则在设定的时间后抛出异常。

  • 相关阅读:
    【LeetCode】Validate Binary Search Tree
    【LeetCode】Search in Rotated Sorted Array II(转)
    【LeetCode】Search in Rotated Sorted Array
    【LeetCode】Set Matrix Zeroes
    【LeetCode】Sqrt(x) (转载)
    【LeetCode】Integer to Roman
    贪心算法
    【LeetCode】Best Time to Buy and Sell Stock III
    【LeetCode】Best Time to Buy and Sell Stock II
    CentOS 6 上安装 pip、setuptools
  • 原文地址:https://www.cnblogs.com/aszeno/p/10311135.html
Copyright © 2011-2022 走看看