我正在尝试制作一个脚本,使用selenium-webdriver每10秒更新一次图像src。
这在节点服务器上运行。 我无法理解为什么在编译期间javascript在setInterval回调中的驱动变量上出现“SyntaxError:Unexpected identifier”的错误。
是不是“deiver”变量在“示例”范围内的funcetion和setInterval回调应该能够访问它吗?
const {Builder, By, Key, until} = require('selenium-webdriver');
var firefox = require('selenium-webdriver/firefox');
var FirefoxProfile = require('firefox-profile');
FirefoxProfile.copyFromUserProfile({name: 'foobar'}, function(err, profile) {
var opts = new firefox.Options();
opts.setProfile(profile.profileDir);
(async function example() {
let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(opts).build();
try {
await driver.get('http://google.com');
var myTimer = setInterval(()=>{
var image = await driver.findElement(By.xpath("//img")); // error is here
var imageSrc = image.getAttribute('src');
},1000*10);
} catch(err) {
console.log(err);
} finally {
await driver.quit();
}
})();
});
错误:
/home/vikas/Development/node/webdriver/index.js:16
var image = await driver.findElement(By.xpath("//img"));
^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:537:28)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
答案 0 :(得分:1)
由于您没有提供任何停止条件,您可以用无限循环替换setInterval
// promisified "setTimeout" to use later
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
(async function example() {
let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(opts).build();
try {
await driver.get('http://google.com');
while(true) { // run forever or use some condition to stop
await delay(1000 * 10) // just wait 10 seconds
var image = await driver.findElement(By.xpath("//img"));
var imageSrc = image.getAttribute('src'); // do something useful, I guess
}
} catch(err) {
console.log(err);
} finally {
await driver.quit();
}
})();