selenium 滑动页面至元素可见

    技术2025-06-03  45

    滚动页面   在自动化操作中,如果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\n”)

    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() 复制代码

    转载自:https://www.cnblogs.com/wanghuijie1/p/12037565.html

    Processed: 0.011, SQL: 9