You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium页面滚动异常求助:无法点击底部加载按钮

问题排查与解决方案

现有代码的核心问题

  1. 固定层级XPath不可靠:页面内容动态加载,元素层级(比如div[7])会随内容增加变化,固定XPath大概率定位失败。
  2. execute_script用法错误:driver.find_element(...).click()返回None,将None传入arguments[0]会导致滚动逻辑完全失效。
  3. 缺失等待逻辑:滚动后元素需要渲染时间,直接查找会因元素未加载抛出异常。

可行解决方案

1. 改用稳定的元素定位方式

放弃固定层级XPath,改用基于元素文本的定位(匹配「See more articles」按钮):

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

2. 显式等待+滚动+点击组合逻辑

先等待按钮可见,再滚动到目标位置(避免被遮挡),最后执行点击:

# 最长等待10秒,直到按钮可见
see_more_btn = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, '//span[text()="See more articles"]'))
)

# 滚动到按钮中心位置(防止底部导航栏遮挡)
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", see_more_btn)

# 点击按钮
see_more_btn.click()

3. 循环滚动加载的兜底方案

若直接滚动到按钮无效,可循环滚动页面底部触发加载,直到按钮出现:

import time

while True:
    try:
        see_more_btn = driver.find_element(By.XPATH, '//span[text()="See more articles"]')
        driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", see_more_btn)
        see_more_btn.click()
        time.sleep(2)  # 等待新内容加载
    except:
        # 找不到按钮则滚动到底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(2)
        # 检测是否已到页面底部(无更多内容)
        current_height = driver.execute_script("return document.body.scrollHeight")
        time.sleep(2)
        new_height = driver.execute_script("return document.body.scrollHeight")
        if current_height == new_height:
            break

额外注意事项

  • 优先使用显式等待替代time.sleep,减少不必要的等待时间。
  • 若按钮被底部固定导航栏遮挡,可手动调整滚动偏移:driver.execute_script("window.scrollBy(0, -100);")。

内容的提问来源于stack exchange,提问作者user22209063

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 06:50:10