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

Selenium操作Cookie Clicker游戏遇到‘stale element not found in the current frame’错误求助

Selenium操作Cookie Clicker游戏遇到‘stale element not found in the current frame’错误求助

嘿,这个问题我之前写这个游戏的自动脚本时也踩过坑!你的思路确实比Angela的方法简洁很多,报错的原因其实是个很典型的Selenium问题——过时元素引用(Stale Element Reference)。

为什么会报错?

你最开始打开页面时获取了store的元素列表,这些元素引用只对应当时页面DOM里的元素。但每次你购买物品后,商店区域会重新渲染:比如物品价格更新、新物品解锁,甚至元素的class属性动态变化,这时候你存在store变量里的旧元素引用就完全失效了,它们不再指向当前页面上的实际元素,自然就会抛出这个错误。

怎么解决?

核心方案就是:每次要执行购买检查时,重新获取商店的元素列表,别一直复用最开始那批过期的引用。另外我还帮你优化了购买逻辑——应该从右往左点商店物品(右边的物品性价比更高,优先买贵的才能更快积累收益),不然全买便宜的会浪费大量cookie。

修改后的代码如下:

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium import webdriver  # 你原来的代码漏了这个关键导入!
import time

options = Options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get("https://orteil.dashnet.org/experiments/cookie/")

big_cookie = driver.find_element(By.ID, "cookie")
timeout = time.time() + 3

while True:
    big_cookie.click()
    if time.time() > timeout:
        # 每次检查购买前重新获取商店元素,确保是最新的DOM引用
        store = driver.find_elements(By.CSS_SELECTOR, "div #store div")
        # 从右往左遍历,优先买最贵/性价比最高的物品
        for element in reversed(store):
            element_class = element.get_attribute("class")
            # 优化class判断逻辑,兼容元素有多个class的情况
            if not element_class or "grayed" not in element_class:
                element.click()
                # 点击后留个小延迟,避免DOM还没更新就继续操作
                time.sleep(0.1)
        timeout = time.time() + 5

额外的优化说明

  1. 补上了你代码里漏掉的from selenium import webdriver导入,不然脚本连启动Chrome都做不到
  2. 把store的获取逻辑移到了每次购买检查的代码块里,确保每次拿到的都是当前页面的最新元素
  3. 用reversed(store)反转遍历顺序,优先买高价值物品,这才是玩这个游戏的高效姿势😉
  4. 优化了class的判断逻辑,避免因为元素有多个class(比如后续可能出现的其他标识类)导致判断失效

备注:内容来源于stack exchange,提问作者kutari studios

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:35:29