尝试使用Selenium和Node JS获得HREF



使用.getAttribute("href">无法从我的web元素中获得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)

addawait到console.log行,它工作了。

console.log(等待链接(指数).getAttribute("href");

最新更新