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

Selenium Python提取JavaScript变量报错:ReferenceError问题求助

解决方法

原因分析

remainingTimeString 大概率不是全局作用域变量,而是定义在某个函数/闭包内部;或者页面还未完全加载时你就执行了JS代码,导致变量尚未初始化。

方案1:等待页面完全加载后再执行

先确保页面所有脚本都执行完毕,再尝试获取变量:

import selenium.webdriver
from selenium.webdriver.support.ui import WebDriverWait

options = selenium.webdriver.FirefoxOptions()
options.add_argument("--headless")

driver = selenium.webdriver.Firefox(options=options)
driver.get('https://shopgoodwill.com/item/151632327')

# 等待页面加载完成(确认document处于ready状态)
WebDriverWait(driver, 10).until(
    lambda d: d.execute_script('return document.readyState') == 'complete'
)

# 尝试从window全局对象获取变量
result = driver.execute_script("return window.remainingTimeString || '未找到变量'")
print(result)

方案2:直接提取页面显示的剩余时间文本

如果变量无法从全局作用域获取,直接抓取页面上显示剩余时间的元素内容更可靠(需根据页面实际结构调整选择器):

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待剩余时间元素加载完成
remaining_time_elem = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located(("css selector", ".countdown-timer"))
)
print(remaining_time_elem.text)

方案3:从页面脚本块中提取变量值

如果前两种方法失效,可以直接定位包含remainingTimeString的脚本标签,用正则提取变量值:

import re

# 获取页面所有脚本标签
scripts = driver.find_elements("tag name", "script")
for script in scripts:
    script_content = script.get_attribute("innerHTML")
    if "remainingTimeString" in script_content:
        # 匹配变量赋值语句
        match = re.search(r'remainingTimeString\s*=\s*["\'](.*?)["\']', script_content)
        if match:
            print(match.group(1))
            break

内容的提问来源于stack exchange,提问作者R.M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:20:19