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

    1、显式等待

    from selenium.webdriver.support import expected_conditions as EC
    
    from selenium.webdriver.support.wait import WebDriverWait
    
        def text_by_xpath(self,loc):
            '''依据元素返回text信息'''
           # / self.logger.debug(loc)
            for i in range(5):
                try:
                    WebDriverWait(self.driver,3,1).until(
                        EC.presence_of_element_located(loc)
                    )
                    text = self.find_element(*loc).text
                    if text!=None:
    
                        return text
                except Exception as e:
                    # self.logger.debug(e)
                    pass
            else:
               # self.logger.debug("无内容返回")
                pass

    在设置时间内,每隔一段时间对页面进行检测

    expected_conditions提供的判断方法:

     除了使用该类,还可使用 is_displayed()方法进行判断元素是否可见

    from selenium import webdriver
    from time import sleep ,ctime
    
    driver = webdriver.Firefox()
    driver.get("http://www.baidu.com")
    
    print(ctime())
    
    for i in range(10):
        try:
            el = driver.find_element_by_id("kw1")
            if el.is_displayed():
                break
        except:pass
        sleep(1)
    
    else:
        print("time out")
    driver.close()
    print(ctime())

    2、隐式等待

    通过一定时长等待页面上某元素加载完成。如果超出设置的时长还没有被加载,则抛出异常

    from selenium import webdriver
    from time import sleep ,ctime
    from selenium.common.exceptions import  NoSuchElementException
    
    driver = webdriver.Firefox()
    driver.implicitly_wait(10)
    driver.get("http://www.baidu.com")
    
    try:
        print(ctime())
        el = driver.find_element_by_id("kw1").send_keys("111")
    except NoSuchElementException as e:
        print(e)
    finally:
        driver.close()
        print(ctime())

    3、sleep休眠方式

    from selenium import webdriver
    from time import sleep ,ctime
    from selenium.common.exceptions import NoSuchAttributeException

    driver = webdriver.Firefox()
    driver.implicitly_wait(10)
    driver.get("http://www.baidu.com")

    try:
    print(ctime())
    el = driver.find_element_by_id("kw1").send_keys("111")
    except NoSuchAttributeException as e
    print(e)
    finally:
    driver.close()
    print(ctime())
  • 相关阅读:
    Dubbo入门微服务框架学习
    CSS学习笔记:溢出文本省略(text-overflow)
    ThreadLocal
    redis事务及乐观锁
    redis的三个特殊数据结构(geospatial、bitmaps、hyperloglogs)
    js日期时间格式化
    SimpleDateFormat 中的yyyy-MM-dd HH:mm:ss.SSS说明
    js中window.location.search的用法和作用。
    MySQL查询表中某个字段的重复数据
    完全卸载Oracle方法(超详细)
  • 原文地址:https://www.cnblogs.com/wbw-test/p/12890352.html
Copyright © 2011-2022 走看看