You need to enable JavaScript to run this app. Python Selenium 统计Justdial评论按钮遇StaleElementReferenceException
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium 统计Justdial评论按钮遇StaleElementReferenceException

问题现象
  • 目标:从指定Justdial商铺页面统计“Load More Reviews”按钮的累计点击次数
  • 运行自动化脚本触发报错:selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  • 原实现逻辑:打开目标商铺页面、关闭首屏弹窗、通过死循环反复定位“Load More Reviews”按钮执行点击操作并计数
  • 原代码存在的过时写法:使用旧版Selenium的chrome_options参数传入浏览器配置

报错根因

  • StaleElementReferenceException 触发于元素引用与当前页面DOM结构脱钩的场景:每次点击“Load More Reviews”后,页面会异步拉取新评论并重绘整个评论区DOM结构,之前获取的元素引用地址会随DOM重绘失效
  • 原代码采用无终止条件的死循环逻辑:当所有评论加载完成后,“Load More Reviews”按钮会被直接从DOM中移除,此时继续执行定位点击逻辑必然触发引用异常
  • 点击操作后没有等待DOM状态稳定,下一轮循环定位元素时刚好处于DOM刷新的过渡期,会随机触发引用失效报错

修正后的可运行代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--disable-notifications")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
url = "目标Justdial商铺页面地址"
driver.get(url)

# 关闭首屏促销弹窗
pop_up = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="best_deal_detail_div"]/section/span')))
pop_up.click()

count = 0
while True:
    try:
        # 每轮循环重新定位按钮,避免旧引用失效
        element = WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable((By.XPATH, "//span[text()='Load More Reviews..']")))
        element.click()
        count += 1
        print(f"已完成第{count}次点击")
        # 等待评论加载完成,确保DOM稳定后再进入下一轮
        WebDriverWait(driver, 10).until(
            EC.invisibility_of_element_located((By.CLASS_NAME, "reviewloading")))
    except:
        # 当按钮不存在(评论全部加载完)时跳出循环
        print(f"评论加载完成,累计点击次数:{count}")
        break

代码调整说明

  • 修正了过时的chrome_options传参写法,适配新版Selenium的API规范
  • 增加了评论加载状态的等待逻辑:点击按钮后等待加载动画消失,确认DOM重绘完成再进入下一轮定位,从根源上避免元素引用过期的问题
  • 增加了异常捕获逻辑:当按钮从DOM中移除(即所有评论加载完成)时自动退出循环,避免无终止的死循环触发运行时报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 08:54:04