美文网首页我爱编程
基于Python的Web自动化(Selenium)之元素等待

基于Python的Web自动化(Selenium)之元素等待

作者: M_派森 | 来源:发表于2018-04-16 11:07 被阅读29次

    简单介绍

    如今大多数Web应用程序使用AJAX技术。当浏览器在加载页面时,页面上的元素可能并不是同时被加载完成的,这给元素的定位增加了困难。如果因为在加载某个元素时延迟而造成ElementNotVisibleException的情况出现,就会降低自动化脚本的稳定性,可以通过设置元素等待改善这个问题造成的不稳定。

    实际操作

    一、显示等待

    显示等待是WebDriver等待某个条件成立时继续执行,否则在达到最大时抛出超时异常(TimeoutException)。废话不多,直接上代码:

    # -*- coding: utf-8 -*-

    from seleniumimport webdriver

    import time

    from selenium.webdriver.common.by import By

    from  selenium.webdriver.support.ui import WebDriverWait

    from selenium.webdriver.support import expected_conditions as EC

    driver = webdriver.Chrome()

    driver.get('https://www.baidu.com/')

    element = WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located((By.ID, 'kw')))

    element.send_keys('selenium')

    time.sleep(5)driver.quit()

    首先需要导入一个“from selenium.webdriver.support import expected_conditionsas EC”,这里命名为“EC”,简单使用。WebDriverWait类是WebDriver提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异常。具体格式如下:

    1.1 WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None)

        driver:浏览器驱动

        timeout:最长超时时间,默认以秒为单位

        poll_frequency:检测的间隔(步长)时间,默认为0.5秒

        ingored_exceptions:超时后的异常信息,默认情况下抛出NoSuchElementException异常

    1.2 until(method,message='')

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

        【until_not(method,message='')   

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

    1.3EC.presence_of_element_located()

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

    二、隐式等待

    相对于显示等待,隐式等待则简单得多。隐式等待是通过一定的时长等待页面上某元素加载完成。如果超出了设置的时长元素没有被加载出来,则抛出NoSuchElementException异常。WebDriver提供了implicitly_wait(),默认设置为0。当然也是可以使用time.sleep()来进行等待。代码如下:

    # -*- coding: utf-8 -*-

    from selenium import webdriver

    import time

    from selenium.common.exceptions import NoSuchElementException

    driver = webdriver.Chrome()

    driver.implicitly_wait(10)

    driver.get('https://www.baidu.com/')

    try:

    print(time.ctime())

    driver.find_element_by_id('kw').send_keys('selenium')

    except NoSuchElementException as e :

    print (e)

    finally:

    print(time.ctime())

    time.sleep(5)

    driver.quit()

    相关文章

      网友评论

        本文标题:基于Python的Web自动化(Selenium)之元素等待

        本文链接:https://www.haomeiwen.com/subject/kyuskftx.html