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

Python中ChromeDriver获取Discord的localStorage token返回None的解决方法

如何通过ChromeDriver在Python中获取Discord验证链接页面的localStorage token值

问题排查

你的代码存在几个关键问题导致无法读取到localStorage中的token:

  • 创建了两个独立的ChromeOptions对象,加载指定用户配置文件的options并未传入driver初始化,导致浏览器使用全新会话,而非保存了token的Profile 38。
  • 页面加载后立即执行读取操作,未等待Discord验证链接完成跳转或localStorage完成写入。
  • recreate_localStorage_script的执行时机过早,未确保页面DOM完全稳定。

修正后的代码实现

import undetected_chromedriver as webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

recreate_localStorage_script = '''
    const iframe = document.createElement('iframe');
    document.head.append(iframe);
    const pd = Object.getOwnPropertyDescriptor(iframe.contentWindow, 'localStorage');
    iframe.remove();    
    Object.defineProperty(window, 'localStorage', pd);
'''

# 合并所有Chrome配置到同一个Options对象
options = webdriver.ChromeOptions()
# 指定要使用的浏览器配置文件
profile = "C:\\Users\\nicvaldy\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 38"
options.add_argument(f"user-data-dir={profile}")
# 添加移动模拟配置
mobile_emulation = {
    "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },
    "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile Safari/535.19"
}
options.add_experimental_option("mobileEmulation", mobile_emulation)

# 初始化driver
driver = webdriver.Chrome(chrome_options=options, use_subprocess=True)
driver.get("https://click.discord.com/ls/click?")

# 等待页面跳转完成(这里以等待页面标题包含Discord为例,可根据实际跳转后的页面调整)
try:
    WebDriverWait(driver, 30).until(
        EC.title_contains("Discord")
    )
    # 页面稳定后重新定义localStorage
    driver.execute_script(recreate_localStorage_script)
    # 读取token
    token = driver.execute_script("return window.localStorage.getItem('token');")
    print('token:', token)
except Exception as e:
    print("页面加载超时或未找到目标内容:", str(e))

# 保持浏览器打开以便调试
input("按回车键关闭浏览器...")
driver.quit()

关键修改说明

  1. 合并配置对象:将用户配置文件和移动模拟参数整合到同一个ChromeOptions中,确保driver使用你保存了Discord登录状态的浏览器配置文件。
  2. 等待页面稳定:使用WebDriverWait设置超时等待,确保页面完成跳转和localStorage写入操作,避免因页面未加载完成导致读取失败。
  3. 调整操作顺序:在页面稳定后再执行localStorage重定义和读取操作,保证操作的有效性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:35:18