[英]How to catch all promises with axios.all?
我正在使用axios和cheerio抓取網頁:
這個網頁有很多鏈接,向下滾動時加載更多(比如facebook )。
我想在向下滾動時抓取每個鏈接,直到到達結尾。
這是我的代碼示例:
cheerio = require('cheerio')
axios = require('axios')
function getLink(id) {
return axios(options).then(function(response) {
// Do stuff...
})
}
function scrollDown() {
axios(scrollOptions).then(function(response) {
$ = cheerio.load(response['data'])
isScrollFinished = ($('.page_more').length == 0)
promises = []
newLinks = $('.link') // Get the new links that were loaded while scrolling
newLinks.each(function() {
promises.push(getLink($(this).attr('id')))
})
axios.all(promises).then(responseArr => {
if(isScrollFinished) {
// Exit script
}
})
if(!isScrollFinished) {
scrollDown()
}
})
}
scrollDown()
這段代碼的問題在於,有時在我退出之前它不會抓取所有鏈接。
這是因為最后一個 axios.all 只會等到最后一個滾動頁面的所有鏈接都被刮掉。
我該如何解決?
我將 promises 數組創建為靜態變量,並且僅在滾動結束時對其調用 axios.all:
cheerio = require('cheerio')
axios = require('axios')
function getLink(id) {
return axios(options).then(function(response) {
// Do stuff...
})
}
function scrollDown() {
if (typeof scrollDown.promises === 'undefined') {
scrollDown.promises = [] // Define static variable if undefined
}
axios(scrollOptions).then(function(response) {
$ = cheerio.load(response['data'])
isScrollFinished = ($('.page_more').length == 0)
newLinks = $('.link') // Get the new links that were loaded while scrolling
newLinks.each(function() {
scrollDown.promises.push(getLink($(this).attr('id')))
})
if(isScrollFinished) {
axios.all(scrollDown.promises).then(responseArr => {
// Exit script
})
}
else {
scrollDown()
}
})
}
scrollDown()
更好的解決方案將很樂意被接受。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.