如何用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'
正确实现方式
你的代码报错主要有两个原因:
- JS代码中函数定义完成后直接调用
login(),两者之间没有分号分隔,导致JS语法解析错误 - 手动拼接字符串传递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
相关产品推荐
相关产品推荐

