Python Selenium 实现指定距离的自动页面滚动

清欢
清欢
发布时间:2026-10-15| 4人浏览过
原创

本文介绍如何利用 Python 的 Selenium 库实现网页自动向下滚动,以触发动态内容加载。通过封装 JavaScript 的 window.scrollBy 方法,结合循环判断当前滚动高度,实现了可配置每次滑动步长和最大总滑动距离的功能。示例代码展示了如何控制 Chrome 浏览器滚动指定像素,适用于需要模拟用户浏览行为的自动化测试场景。

Selenium 自动滚动页面的核心原理

在使用 Selenium 控制 Chrome 浏览器时,有时需要自动向下滚动页面以触发懒加载内容。实现这一功能的核心在于执行 JavaScript 脚本。

基础滚动代码

browser.execute_script("window.scrollBy(0,300)")

最基本的滚动操作可以通过执行以下代码实现,该脚本会使页面立即向下移动 300 个像素:

封装滚动工具函数

为了更灵活地控制滚动过程,例如限制最大滚动距离或模拟真实用户的滑动节奏,可以封装一个工具函数。

滚动函数实现逻辑

def roll_window_to_bottom(browser, stop_length=None, step_length=500):
    """selenium 滚动当前页面,向下滑
    :param browser: selenium的webdriver
    :param stop_length: 滑动的最大值
    :param step_length: 每次滑动的值
    """
    original_top = 0
    while True:  # 循环向下滑动
        if stop_length:
            if stop_length - step_length < 0:
                browser.execute_script("window.scrollBy(0,{})".format(stop_length))
                break
            stop_length -= step_length
        browser.execute_script("window.scrollBy(0,{})".format(step_length))
        time.sleep(0.5 + random.random())  # 停顿一下
        check_height = browser.execute_script(
            "return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;")
        if check_height == original_top:  # 判断滑动后距顶部的距离与滑动前距顶部的距离
            break
        original_top = check_height

完整使用示例

以下是具体的使用示例,展示了如何初始化浏览器并调用滚动函数:

主程序调用代码

from selenium import webdriver
import time
import random


def roll_window_to_bottom(browser, stop_length=None, step_length=500):
    """selenium 滚动当前页面,向下滑
    :param browser: selenium的webdriver
    :param stop_length: 滑动的最大值
    :param step_length: 每次滑动的值
    """
    original_top = 0
    while True:  # 循环向下滑动
        if stop_length:
            if stop_length - step_length < 0:
                browser.execute_script("window.scrollBy(0,{})".format(stop_length))
                break
            stop_length -= step_length

        browser.execute_script("window.scrollBy(0,{})".format(step_length))
        time.sleep(0.5 + random.random())  # 停顿一下
        check_height = browser.execute_script(
            "return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;")
        if check_height == original_top:  # 判断滑动后距顶部的距离与滑动前距顶部的距离
            break
        original_top = check_height


def main():
    option = webdriver.ChromeOptions()
    option.add_argument('lang=zh_CN.UTF-8')  # 设置
    browser = webdriver.Chrome(chrome_options=option, desired_capabilities={"page_load_strategy": "none"})
    browser.get("http://news.baidu.com/")
    roll_window_to_bottom(browser, stop_length=700)


if __name__ == '__main__':
    main()

以上介绍了使用 Python Selenium 实现指定距离自动滚动的完整流程。更多关于 Selenium 自动化操作的内容,欢迎查阅本站其他相关文章或继续浏览后续教程,感谢支持!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。