• selenium元素等待及滚动条滚动


        selenium三大等待,sleep(强制)、implicitlyWait(隐式等待)、WebDriverWait(显式等待),主要记一下最后面的WebDriverWait。

        WebDriverWait是三大等待中最常用也是最好用的一种等待方式,比起另外两种而言,B格更高、更智能。写法为:

    #WebDriverWait(driver,等待总时长,查询间隔时间).until(EC.visibility_of_element_located((By.XPATH,Xpath公式)))
    # 例如:
    cj = '//span[text()="19/05/27"]/parent::p/parent::div/preceding-sibling::div[@class="announce-cont clearfix"]//a[text()="查看成绩"]'
    WebDriverWait(driver,30,0.5).until(EC.visibility_of_element_located((By.XPATH,cj)))
    

        在iframe中也可以使用WebDriverwait,例如:

    WebDriverWait(driver,30,0.5).until(EC.frame_to_be_available_and_switch_to_it("login_frame_qq"))
    # 其中"login_frame_qq"是iframe的name属性;
    # "EC.frame_to_be_available_and_switch_to_it"这句话的意思是等待并切换至,也就是说这句话等同"EC.visibility_of_element_located"+"driver.switch_to_frame"
    

      

        例子中的等待含义为总时长30S,每间隔0.5S查询一次until括号中的函数。EC为selenium.webdriver.support.expected_conditions的缩写,visibility_of_element_located的用法是查询后跟元祖中指定的元素是否可见。

        要格外注意的是visibility_of_element_located()中只能传入一个函数,所以一般使用(By.XPATH,xpath)源码:

    class visibility_of_element_located(object):
        """ An expectation for checking that an element is present on the DOM of a
        page and visible. Visibility means that the element is not only displayed
        but also has a height and width that is greater than 0.
        locator - used to find the element
        returns the WebElement once it is located and visible
        """
        def __init__(self, locator):
            self.locator = locator
    
        def __call__(self, driver):
            try:
                return _element_if_visible(_find_element(driver, self.locator))
            except StaleElementReferenceException:
                return False
    

      再来看一下滚轮滑动的几种用法

      1.滑动到指定元素顶端显示:

    driver.execute_script('argument[0].scrollIntoView();',driver.find_element_by_xpath(xpath)) 

      2.滑动到指定元素底端显示:

    driver.execute_script('argument[0].scrollIntoView(false);',driver.find_element_by_xpath(xpath))

      3.页面滑动到底端:

    driver.execute_script('windows.scrollto(0,document.body.scrollHeight)')
    

      4.页面滑动到顶端:

    driver.execute_script('windows.scrollto(document.body.scrollHeight)')
    

      其中包含指定元素的使用时只用注意scrollIntoView后是否跟随false,有则底端、无则顶端;其次页面滑动时只用注意最后是否从0开始,从0开始则为底端、无则顶端

      顺带说一下driver.execute_script()这个函数,这个函数括号内主要跟随js语句

      用法例如:

    driver.execute_script('argument[0].scrollIntoView(false);'
                              'var a = argument[1]',driver.find_element_by_xpath(xpath),num1)    
    # 其带入的参数没有数量限制,只是语法必须使用js语法
    

      

  • 相关阅读:
    linux常用脚本
    shell学习笔记
    Linux常用命令List
    Centos7部署Zabbix
    centos7安装nagios步骤
    nagios报错HTTP WARNING: HTTP/1.1 403 Forbidden解决方法
    U盘安装CentOS7
    Thread线程控制之sleep、join、setDaemon方法的用处
    EfficientDet框架详解 | 目前最高最快最小模型,可扩缩且高效的目标检测(附源码下载)
    ubuntu18.04 安装多版本cuda ,原来版本为9.0,在新增8.0
  • 原文地址:https://www.cnblogs.com/keima/p/10972260.html
Copyright © 2020-2023  润新知