Python+Selenium:3种等待设置

Posted daisyatcnblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python+Selenium:3种等待设置相关的知识,希望对你有一定的参考价值。

1.强制等待—sleep()

设置固定休眠时间,python 的time 包提供了休眠方法sleep() ,导入time 包后就可以使用sleep()进行脚本的执行过程进行休眠。
无论浏览器加载是否完成,程序都要等待设定的时间,继续执行下面的代码

import time
time.sleep(3)

2.隐式等待—implicitly_wait()

implicitly_wait(xx):设置等待时间为xx秒,等待元素加载完成,如果到了时间元素没有加载出,就抛出一个NoSuchElementException的错误。
注意:隐性等待对整个driver的周期都起作用,所以只要设置一次即可。隐性等待,最长等30秒

driver.implicitly_wait(30)

3.显示等待—WebDriverWait()

导入WebDriverWait包后可以使用。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异常。
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
或from selenium.webdriver.support import expected_conditions As EC

WebDriverWait(driver,timeout,poll_frequency,ignored_exceptions=None).until()后面可以还加.click()等
driver - WebDriver 的驱动程序(Ie, Firefox, Chrome 或远程)
timeout - 最长超时时间,默认以秒为单位
poll_frequency - 休眠时间的间隔(步长)时间,默认为0.5 秒
ignored_exceptions - 超时后的异常信息,默认情况下抛NoSuchElementException 异常
until中可以用lambda、excepted_conditions等,如果使用excepted_conditions,则需要导入emcepted condition包
实例:
登录邮箱后点击【写信】,两种实现方法:

#lambda函数实现
WebDriverWait(driver, 5, 0.5, ignored_exceptions=None).until(lambda x: driver.find_element_by_xpath("//a[contains(text(),‘设置‘)]")).click()
#expected_conditions实现
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
loc = "//span[contains(text(),‘写 信‘)]"
WebDriverWait(driver, 5, 0.5, ignored_exceptions=None).until(EC.presence_of_element_located((By.XPATH, loc))).click()

4.三种方式的优缺点:

1.强制等待使用最简单,但是无论页面加载完成都要加载设定的时间长度,不够灵活
2.隐式等待浏览器会在设定的时间内不断再DOM种刷新查询该元素,知到出现位置,会降低测试性能。
3.显示等待,用法相对于前两种相对复杂,但是也是最灵活的。

 

以上是关于Python+Selenium:3种等待设置的主要内容,如果未能解决你的问题,请参考以下文章

Python+Selenium自动化篇-8-设置等待三种等待方法

python+selenium2自动化---设置元素等待

selenium3+python自动化15-三种等待方式

selenium 设置等待时间

selenium+python的三种等待

Python +selenium之设置元素等待