无法使用 .getAttribute("href") 从我的网络元素中获取 href。我可以让它在单个变量上工作,但在它循环遍历我的数组时不能。
const {Builder, By, Key, until} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to webscraper.io
await driver.get('https://webscraper.io/test-sites');
// Scrape links
let links = await driver.findElements(By.xpath('//*[@class="row test-site"]/div/h2/a'))
// loop through links and print
console.log('\nFound ' + links.length + ' Links total.\n')
for (let index = 0; index < links.length; index++) {
console.log(links[index].getAttribute("href"));
}
}
finally{
driver.quit();
}
})();
我收到以下错误:
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
(node:81217) UnhandledPromiseRejectionWarning: Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:54431
at ClientRequest.<anonymous> (/Users/eric/Dropbox/Javascript/node_modules/selenium-webdriver/http/index.js:262:15)
at ClientRequest.emit (events.js:315:20)
at Socket.socketErrorListener (_http_client.js:469:9)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:81217) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
答案 0 :(得分:0)
在 console.log 行中添加了 await 并且它起作用了。
console.log(await links[index].getAttribute("href"));