【发布时间】:2020-07-13 21:46:04
【问题描述】:
我正在使用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 只等到 last 滚动页面的所有链接都被抓取。
我该如何解决这个问题?
【问题讨论】:
-
// Do Stuff表示模棱两可。是故意不显示实现代码,还是实际上是它本身 -
故意不显示代码的实现,与问题无关