zoukankan      html  css  js  c++  java
  • Selenium—滚动页面至元素可见

    滚动页面

      在自动化操作中,如果web页面过长,而我们需要的元素并不在当前可视页面中,那么selenium就无法对其进行操作;此时,我们就需要像平时操作浏览器一样来滚动页面,使我们需要操作的对象可见!

      滚动页面的方法:

    • window.scrollBy()
      • window.scrollBy(0,500)     向下滚动500个像素

      • window.scrollBy(0,-500)   向上滚动500个像素

      • window.scrollBy(500,0)     向右滚动500个像素

      • window.scrollBy(-500,0)   向左滚动500个像素

    • 使用方式:

      • 在 开发者工具--Console中输入以上内容,即可实现页面滚动

      • 示例:window.scrollBy(0,500)    向下滚动500个像素

    Selenium中实现滚动页面

    • driver.execute_script('window.scrollBy()')
    • driver.execute_script("arguments[0].scrollIntoView();", ele)  滚动至元素ele可见

     代码示例:

    from selenium import webdriver
    import time
    
    driver = webdriver.Chrome()
    driver.implicitly_wait(10)
    # 设置窗口大小
    driver.set_window_size(800, 700)
    
    driver.get('http://baidu.com')
    
    # 百度输入框输入 selelnium python 回车
    driver.find_element_by_id("kw").send_keys("selenium python
    ")
    
    time.sleep(2)
    # 向下滚动200个像素
    driver.execute_script('window.scrollBy(0,200)')
    
    time.sleep(2)
    # 滚动至元素ele可见位置
    eles = driver.find_elements_by_css_selector('#rs table tr th a')
    ele = eles[0]
    driver.execute_script("arguments[0].scrollIntoView();",ele)
    
    time.sleep(2)
    # 向右滚动200个像素
    driver.execute_script('window.scrollBy(200,0)')
    
    time.sleep(2)
    driver.quit()
  • 相关阅读:
    ftp的虚拟用户的使用
    系统进程与线程
    mysql 100%占用的解决
    两张神图介绍python3和 2.x与 3.x 的区别
    python3中__get__,__getattr__,__getattribute__的区别
    Python 数据图表工具的比较
    Spark入门(Python)
    别学框架,学架构
    Python垃圾回收机制
    pyextend库-accepts函数参数检查
  • 原文地址:https://www.cnblogs.com/wilson-5133/p/10996810.html
Copyright © 2011-2022 走看看