You need to enable JavaScript to run this app. Python Selenium循环二次运行触发stale element reference错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium循环二次运行触发stale element reference错误求助

注:目标站点存在安全风险,不建议直接访问,以下方案仅针对技术问题本身

问题原因
  • 你代码中首次进入列表页时预抓取了所有视频链接元素存入Vids列表,当你点击第一个元素进入详情页后,执行driver.get(URL)返回列表页,此时页面DOM已刷新,Vids列表中存储的旧元素全部脱离当前文档,第二次循环调用旧元素点击就会触发StaleElementReferenceException。
  • 附带其他可优化问题:
    • CSV写入用w模式会覆盖之前写入的所有数据,最终仅会保存最后一条记录
    • 异常捕获语法错误,except A or B仅会捕获A的异常,正确写法是except (A, B)
    • 详情页标题的XPath写死了post id,不同视频的post id不同,会导致后续标题抓取失败
    • 循环内重复获取元素列表没有实际作用,无法解决旧元素失效的问题
解决方案

推荐先预抓取所有视频的跳转链接存入本地列表,再循环访问每个链接抓取数据,完全规避元素失效问题。

修正后代码
import time
import csv
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 selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException

URL = 'https://avbebe.com/archives/category/高清中字/page/5'
PATH = "你的chromedriver本地路径"
options = webdriver.ChromeOptions()
# 此处保留你原有options配置

driver = webdriver.Chrome(executable_path=PATH, options=options)
driver.get(URL)
time.sleep(5)

# 先预抓取所有视频的跳转链接,存为字符串列表,完全规避元素失效问题
link_elements = WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, 'entry-thumbnails-link')))
vid_links = [elem.get_attribute('href') for elem in link_elements]

# CSV初始化放在循环外,仅写入一次表头
with open('data.csv', 'w', newline='', encoding = "utf-8") as f:
    fieldnames = ['Title', 'Tags', 'URL']
    thewriter = csv.DictWriter(f, fieldnames=fieldnames)
    thewriter.writeheader()

    # 循环直接访问每个视频详情页
    for vid_link in vid_links:
        driver.get(vid_link)
        time.sleep(3)
        VidUrl = driver.current_url
        # 改用通用标题XPath,不绑定固定post id
        VidTitle = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, '//h1/a'))).text
        VidTag = ""
        try:
            VidTags = driver.find_elements_by_class_name('tags')
            for tag in VidTags:
                VidTag = tag.find_element_by_tag_name('a').text
        except (NoSuchElementException, StaleElementReferenceException):
            pass

        thewriter.writerow({'Title': VidTitle, 'Tags': VidTag, 'URL': VidUrl})
        print('done')        

driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 06:39:00