我目前正在关注一个使用 node.js 进行网页抓取的 youtube 视频。 (https://www.youtube.com/watch?v=TzZ3YOUhCxo&ab_channel=AaronJack)
我设法按照教程进行操作并且它有效,所以我尝试做我自己的示例,但由于某种原因它失败了,我不知道为什么。
我附上了以下代码:
const puppeteer = require('puppeteer')
async function scrapeProduct(url){
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto(url)
const [el] = await page.$x('//*[@id="s7viewer_swatches_listbox"]/div[1]/div/div')
const src = await el.getProperty('src')
const image = await src.jsonValue()
console.log({image})
browser.close()
}
scrapeProduct('https://groceries.asda.com/product/regular-cola/coca-cola-classic-bottle/1000020585281')
答案 0 :(得分:0)
您收到此警告的原因是您忽略了 Promise 将被拒绝的情况。要使用 async/await
处理它,您可以将代码包装在 try/catch
块中:
try {
const result = await Promise.reject(30); // you should replace it with your async function that may reject
} catch (err) {
// handle the error
}
就你而言:
async function scrapeProduct(url) {
try {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto(url)
const [el] = await page.$x('//*[@id="s7viewer_swatches_listbox"]/div[1]/div/div')
const src = await el.getProperty('src')
const image = await src.jsonValue()
console.log({image})
browser.close()
} catch(err) {
// handle the error
console.log('error: ', err);
}
}