【发布时间】:2021-06-30 07:33:56
【问题描述】:
我在 node.js 中使用cheerio 和 axios 抓取多个页面 我在使用 Promises 时遇到了困难,如果我点击最后一页,有人可以帮我返回 JSON 吗?谢谢!
const getWebsiteContent = async (url) => {
await axios.get(url).then(res => {
const $ = cheerio.load(res.data)
pageNum = getTotalpages($); // Get the pagination
console.log(url);
//Some scraping here
})
indexPage++; // Increment to the next page
const nextPageLink = baseUrl + '&page=' + indexPage; // get next page
if (indexPage > pageNum) {
var editedText = text.slice(0, text.length - 1);
editedText += ']}';
editedText = JSON.parse(editedText); // I want to return this and use elsewhere
return editedText;
}
setTimeout(async () => {
getWebsiteContent(nextPageLink); // Call itself
}, 1000);
}
var myJSON= await getWebsiteContent(baseUrl); // something like this
【问题讨论】:
-
我在一些my answers 中使用
asyncUnfold。我写这些已经有一段时间了,但它非常适合这种问题。如果今晚晚些时候我有时间,我可以向您展示如何使用异步生成器:D -
您要返回哪个 JSON?
-
1:谢谢,我等着! 2:在 if(indexPage>pageNum) 中,我连接 JSON 字符串的最后一位,将其解析为 JSON。我想返回该 JSON。
-
不要混用
async/await、.then()和传递回调。将setTimeout包装在一个promise 中,并决定一种处理promise 的风格。
标签: javascript node.js recursion web-scraping promise