scroll_by_amount · scroll_to_element · scroll_to_element_with_offset — 页面滚动的三种 Selenium 原生 API 演示
演示 Selenium 的 三种滚动方式:按偏移量滚动、滚动到元素可见、滚动到元素并带偏移。Selenium 4.2+ 原生提供,不再依赖 JavaScript 注入 。
📋 参数速查表
| API | 参数 | 说明 |
|---|---|---|
| scroll_by_amount(dx, dy) | dx/dy | 水平/垂直偏移(正=右下,负=左上) |
| scroll_to_element(target) | target | 目标元素,自动滚到完全可见 |
| scroll_to_element_with_offset(target, dx, dy) | target/dx/dy | 滚到元素后再加偏移(常用负 dy 避固定导航栏) |
⚠️ 常见陷阱(4 个)
scroll_to_element_with_offset(target, 0, -100) 额外向上留间距。driver.execute_script("arguments[0].scrollIntoView()", el) 兜底。scroll_by_amount() 等方法,比旧版 driver.execute_script("window.scrollBy...") 更稳定。scroll_by_amount 以当前视口为原点滚动;scroll_to_element 以元素边界自动对齐;scroll_to_element_with_offset 在滚到元素的基础上再加偏移,最适合避开固定导航栏遮挡。
# -*- coding: utf-8 -*-
# scroll.py —— Selenium 原生滚动 API 完整演示
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome()
driver.get("https://autotest-505.pages.dev/mouse_op_tech_sections/mouse_scroll_tech.html")
actions = ActionChains(driver)
# ── ① scroll_by_amount(dx, dy) ──────────────────────
# 按像素偏移量滚动(正=向下/向右,负=向上/向左)
actions.scroll_by_amount(0, 500).perform() # 向下滚 500px
time.sleep(1)
actions.scroll_by_amount(0, -300).perform() # 向上滚 300px
# ── ② scroll_to_element(target) ────────────────────
# 滚动直到目标元素完全可见(底部对齐视口)
target = driver.find_element(By.ID, "submit-btn")
actions.scroll_to_element(target).perform()
# ── ③ scroll_to_element_with_offset(target, dx, dy) ──
# 滚到元素后再加偏移微调(最常用:避开固定导航栏遮挡)
actions.scroll_to_element_with_offset(target, 0, -80).perform()
# 元素上方额外留 80px 间距,避开 70px 高的顶部导航栏
# ── 旧版兼容方案(JavaScript 注入) ──────────────────
# Selenium 4.1 及以下版本没有原生 scroll_by_amount
driver.execute_script("window.scrollBy(0, 500)")
driver.execute_script("arguments[0].scrollIntoView()", target)
# ── 方法对比速查 ──
# scroll_by_amount(dx, dy) 锚点: 当前视口 常用度: ★★★☆☆
# scroll_to_element(target) 锚点: 元素边界 常用度: ★★★★☆
# scroll_to_element_with_offset 锚点: 元素+偏移 常用度: ★★★★★(避遮挡必备)
# 2. 关闭浏览器
driver.quit()