python+selenium中的Implicit Waits/Explicit Waits/sleep以及Fluent waits

来源:互联网 发布:sae php 编辑:程序博客网 时间:2024/06/03 17:41

selenium定位元素时,有些元素需要等待一段时间始出来,从而才能定位到,继而才能进行下一步的操作,详细了解一下selenium中几种等待的方式

sleep

sleep是time模块下的一个方法,默认单位是seconds

from time import sleepfrom selenium import webdriverdriver = webdriver.Chrome()driver.get("http://www.baidu.com")sleep(5)
  • Explain
    在打开网址www.baidu.com后,会等待5秒钟后再进行下面的步骤。
  • 缺点
    很明显,每一个元素可能需要加载的地方都需要设置sleep等待时间,非常繁琐

Implicit Wait

selenium webdriver提供的方法之一,隐式等待

from time import sleepfrom selenium import webdriverdriver = webdriver.Chrome()driver.implicitly_wait(10) # 设置隐式等待时间为10sdriver.get("http://www.baidu.com")driver.find_element_by_css_selector("#kw").send_keys("Python")
  • Explain
    单位同样是seconds,不同的是隐式等待最多等待10s,如果10s内元素仍加载不了(判断元素是否存在于DOM中,判断频率默认是250 milliseconds),就会抛异常;如果元素“#kw”很快就加载出来了,就不用等待10s,会直接操作元素。

  • 优点
    Once set, the implicit wait is set for the life of the WebDriver object. 隐式等待在driver的整个生命周期内都有效。也就是说,driver在没有被close()之前,定位每个元素时,都会有隐式等待的10s,也就是说,只需要设置一次,所有的元素都可有最多10s的等待加载的时间。相比sleep要设置很多次,很方便了。

  • 缺点
    implicit wait是检查元素是否存在于DOM,如果元素已经存在于DOM,就会结束等待,进行下一步操作;而有些元素可能已经存在于DOM,但是还需等待一段时间才能到可点的状态(clickable),因此使用implicit wait仍会因为等待时间不足而报错(比如,下拉框中元素的选择)

Explicit Wait

selenium webdriver提供的方法之一,显示等待

from selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Chrome()driver.get("http://www.baidu.com")wait = WebDriverWait(driver, 10) # 设置显示等待时间为10selement = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#kw')))# 判断条件driver.find_element_by_css_selector("#kw").send_keys("Python")
  • Explain
    显示等待是条件判断,判断元素#kw可点了,再去操作元素;如果#kw不可点,默认每50
    milliseconds去判断下条件,如果10s内还不可点,就抛出异常。(更多的条件判断见官方文档:http://selenium-python.readthedocs.io/waits.html)

  • 优点
    弥补了implicit wait的不足,可以通过判断一些条件,再去决定是否等待下去

  • 缺点
    当然是写起来麻烦啦,如果要用到,可以考虑封装起来用

Fluent Waits

FluentWait是Java selenium中的另一种wait的方式,与Explicit Wait类似,可以定义等待结束的条件、等待的最大时长以及判断元素是否满足条件的频率

综上:Selenium+Python建议implicit wait与explicit wait结合使用;在有必要的时候要用explicit wait

References
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html
http://toolsqa.com/selenium-webdriver/implicit-explicit-n-fluent-wait/
http://selenium-python.readthedocs.io/waits.html#implicit-waits

原创粉丝点击