JavaScript Selenium:Twitter登录脚本driver.sleep失效问题排查
问题:Twitter登录自动化脚本中driver.sleep未生效
我编写了一个Twitter登录自动化脚本,在第21行设置了隐式等待,第34行调用driver.sleep()进行等待,但该driver.sleep()并未生效。尝试过多种等待组合,也通过谷歌搜索寻找解决方案,但问题仍未解决。
'use strict'; const {Browser,Builder, By, Key} = require('selenium-webdriver'); const config = require('./config'); const {TOTP} = require('totp-generator'); function getRandomNum() { const min = 5000; const max = 10000; return Math.random() * (max - min) + min; } function getToptpToken() { const { otp, expires } = TOTP.generate(config.twitter.toptp.token); return otp; } async function twitterLogin() { const url = 'https://x.com/i/flow/login'; const driver = await new Builder().forBrowser(Browser.CHROME).build(); try{ await driver.manage().setTimeouts({ implicit: 20000 }); await driver.get(url) const username = await driver.findElement(By.xpath("//input[@autocomplete='username']")); await username.sendKeys(config.twitter.login); await username.sendKeys(Key.RETURN); const phoneNumber = await driver.findElement(By.xpath("//input")); await phoneNumber.sendKeys(config.twitter.phone); await phoneNumber.sendKeys(Key.RETURN); const password = await driver.findElement(By.xpath("//input[@autocomplete='current-password']")); await password.sendKeys(config.twitter.pass); await password.sendKeys(Key.RETURN); const totpToken = await driver.findElement(By.xpath("//input")); await totpToken.sendKeys(Key.RETURN); await driver.sleep(getRandomNum()); } catch (error){ if(error === 'NoSuchElementError'){ console.error(error.message); } }finally { await driver.quit(); } } twitterLogin()
问题已解决,修复点如下:
- 修复
getRandomNum函数:原函数返回浮点数,而driver.sleep()需要整数类型的毫秒数,修改为返回整数:function getRandomNum() { const min = 5000; const max = 10000; return Math.floor(Math.random() * (max - min) + min); } - 适配账号未启用双因素认证(2FA)的场景:脚本中强行定位TOTP输入框的逻辑会抛出异常,代码直接进入catch块,还未执行到
driver.sleep()就进入finally块关闭了浏览器。移除不必要的TOTP输入逻辑,或者添加判断逻辑确认是否存在该输入框再执行操作。
内容的提问来源于stack exchange,提问作者kaka
相关产品推荐
相关产品推荐

