Python Selenium 实现指定距离的自动页面滚动
本文介绍如何利用 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 自动化操作的内容,欢迎查阅本站其他相关文章或继续浏览后续教程,感谢支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













