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

Selenium添加while循环翻页报Stale element reference异常

问题根因

报错StaleElementReferenceException(失效元素引用异常)的核心原因有3个:

  • 元素定位逻辑写在了while循环外:首次打开页面获取的jobTitle、companyName是第一页DOM的元素引用,点击下一页后页面DOM整体刷新,旧的元素引用和新页面完全脱钩,再调用.text属性就会触发元素不存在的报错。
  • 点击下一页后没有等待新页面加载完成,代码直接操作旧的失效元素。
  • 逻辑bug:arrGlobalText初始化放在了循环内部,每次翻页都会清空之前爬取的内容,最终只能拿到最后一页的数据;且代码先存储WebElement对象、后提取文本,翻页后对象失效就无法再读取内容。
修复后可运行代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
import time
import csv

url = "https://www.welcometothejungle.com/fr/jobs?query=&groupBy=job&sortBy=mostRelevant&page=1&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Logiciels&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Big+Data&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=SaaS+%2F+Cloud+Services&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Intelligence+artificielle+%2F+Machine+Learning&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Cybers%C3%A9curit%C3%A9&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Application+mobile&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Objets+connect%C3%A9s&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Robotique&refinementList%5Bsectors_name.fr.Tech%5D%5B%5D=Blockchain"
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
driver.maximize_window()
# 全局结果数组移到循环外,仅初始化一次,避免翻页清空历史数据
arrGlobalText = []
p = 1
while p < 10:
    # 每进入新页面,重新定位当前页的元素,获取有效DOM引用
    jobTitle = driver.find_elements(By.CLASS_NAME, "ais-Highlight-nonHighlighted")
    companyName = driver.find_elements(By.CLASS_NAME, "sc-7dlxn3-6")
    
    # 定位后立刻提取文本内容存储,不保存易失效的WebElement对象
    for i in range(len(jobTitle)):
        arrGlobalText.append([jobTitle[i].text, companyName[i].text])
    
    # 校验下一页按钮是否可用,到达最后一页直接终止循环
    nextButton = driver.find_elements(By.CLASS_NAME, 'ais-Pagination-item--nextPage')
    if len(nextButton) == 0 or "ais-Pagination-item--disabled" in nextButton[0].get_attribute("class"):
        break
    nextButton[0].click()
    # 等待新页面内容加载完成,网络差时可适当调大等待时长
    time.sleep(2)
    p += 1

print(arrGlobalText)
driver.quit()
优化建议
  • 代码中用的time.sleep()固定等待可以替换为Selenium显式等待,判断职位元素加载完成后再执行后续逻辑,爬取效率和稳定性更高。
  • 定位公司名用的类名sc-7dlxn3-6是前端构建时自动生成的随机类名,网站发版后很容易失效,建议替换为基于DOM层级的相对定位方式,降低后续维护成本。
  • 多页爬取建议增加异常捕获逻辑,避免单页加载异常导致整个爬取任务中断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 15:30:48