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

如何用Python Selenium正确调用execute_script执行Discord登录JS代码?

Discord自动登录:Python Selenium调用execute_script的正确方式

需求

想要通过浏览器控制台的JS代码实现Discord自动登录,目前正在学习Python,完全不懂JS,需要用Python Selenium的execute_script方法调用这段JS代码。

原控制台JS代码

function login(token) {
    setInterval(() => {
      document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`
    }, 50);
    setTimeout(() => {
      location.reload();
    }, 2500);
  }

login(token);

失败的Python尝试

token = 'token'
driver.execute_script('return function login(token) {setInterval(() => {document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`}, 50);setTimeout(() => {location.reload();}, 2500);}login('+"'"+f'{token}'+"');')

报错信息

selenium.common.exceptions.JavascriptException: Message: javascript error: Unexpected identifier 'login'

正确实现方式

你的代码报错主要有两个原因:

  1. JS代码中函数定义完成后直接调用login(),两者之间没有分号分隔,导致JS语法解析错误
  2. 手动拼接字符串传递token时,引号处理混乱,容易引发语法问题

推荐两种更安全的写法:

写法一:保留原函数结构,通过参数传递token

token = '你的Discord令牌内容'
# 把完整JS代码作为字符串,用arguments[0]接收Selenium传入的token参数
js_script = '''
function login(token) {
    setInterval(() => {
      document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`
    }, 50);
    setTimeout(() => {
      location.reload();
    }, 2500);
}
login(arguments[0]);
'''
driver.execute_script(js_script, token)

写法二:简化代码,直接执行逻辑

可以去掉函数定义,直接执行核心逻辑,同样用arguments[0]接收token:

token = '你的Discord令牌内容'
js_script = '''
setInterval(() => {
  document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${arguments[0]}"`
}, 50);
setTimeout(() => {
  location.reload();
}, 2500);
'''
driver.execute_script(js_script, token)

注意事项

  • 确保你已经先打开了Discord的页面(比如driver.get('https://discord.com/login')),再执行这段JS代码
  • Discord可能会检测到这种登录方式,存在账号风险,请谨慎使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:05:18