selenium三个等待方法

时间:2019-10-31
本文章向大家介绍selenium三个等待方法,主要包括selenium三个等待方法使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

为什么需要等待时间:页面加载需要时间,如果页面没有加载完成,直接去定位,可能定位不到元素

1、强制等待:

import time

time.sleep(2) 不管有没有完成加载,必须等待2秒

2、隐式等待:

driver = webdriver.Chrome()
driver.implicity_wait(10)
driver.get('http://www.baidu')
implicity_wait()默认参数的单位为妙,首先这10秒并非一个固定的等待时间,它并不影响脚本的执行速度。其次,它并不针对页面上的某一元素进行等待。当脚本执行到某个元素定位时,如果元素可以定位到,则继续执行;如果元素定位不到,则它将以轮询的方式不断地判断元素是否被定位到。假设在第六秒定位到了元素则继续执行,若直到超出设置的时长10秒还没有定位到元素,则抛出异常。
3、显式等待:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver,5,0.5).until(
EC.presence_of_element_located((By.ID,'kw'))
)
element.send_keys('hello')
WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None)
driver:浏览器驱动
timeout:最长超过时间,默认以秒为单位
poll_frequency:监测的时间间隔,默认为0.5秒
ignored_exceptions:超时后的异常信息,默认情况下抛NoSuchElementException异常
WebDriverWait一般有until和until_not方法配合使用
until(method,message)
until_not(method ,message)
如果成功,则执行下一步,否则继续等待,直到超过设置的最长时间,抛出异常

注意:显式等待与隐式等待可以同时使用,等待时间为两者中最大的

原文地址:https://www.cnblogs.com/aiyumo/p/11771859.html