zoukankan      html  css  js  c++  java
  • python中selenium操作下拉滚动条

    UI自动化中经常会遇到元素识别不到,找不到的问题,原因有很多,比如不在iframe里,xpath或id写错了等等;但有一种是在当前显示的页面元素不可见,拖动下拉条后元素就出来了。

    在python中有几种方法解决这种问题,简单介绍下,给需要的人:

    使用js脚本直接操作

      js="var q=document.getElementById('id').scrollTop=10000"
      driver.execute_script(js)
    

      js="var q=document.documentElement.scrollTop=10000"
      driver.execute_script(js)
    

    这里的id为滚动条的id,但js中没有xpath的方法,所以滚动条没有id的网页此方法不适用

    使用js脚本拖动到提定地方

      target = driver.find_element_by_id("id_keypair")
      driver.execute_script("arguments[0].scrollIntoView();", target) #拖动到可见的元素去
    

    这个方法可以将滚动条拖动到需要显示的元素位置,此方法用途比较广,可以使用

    前段时间使用robotframe work框架时,selenium2library里面有一个非常好用的功能Focus,会自动定位到元素,研读一下源码:

      def focus(self, locator):
          """Sets focus to element identified by `locator`."""
          element = self._element_find(locator, True, True)
          self._current_browser().execute_script("arguments[0].focus();", element)
    

    从源码中我们可以看到,此方法与我们在python自己写的方法二)一致,工具给我们做了封装。

  • 相关阅读:
    Windows上安装PyV8
    Windows鼠标右键菜单添加SublimeText打开选项
    Windows使用Python虚拟环境
    Windows同时安装Python2和Python3
    Windows使用Cmder
    Visual Studio Code配置
    Windows 10使用Tesseract-OCR出现WindowsError: [Error 2]
    用pymysql代替MySQLdb
    使用python来搞定redis的订阅功能
    来写一个最基本的装饰器吧!
  • 原文地址:https://www.cnblogs.com/TD1900/p/13813078.html
Copyright © 2011-2022 走看看