【发布时间】:2019-05-06 16:09:56
【问题描述】:
我期待:
- 打开一个已知的 URL
(www.source.com/1 below) - 抓取该页面上的所有 URL
(e.g. www.urllookingfor.com/1 to .../10)并登录到控制台 - 从该页面抓取一个新的 URL
(e.g. www.source.com/2) - 加载下一页并重复该过程 X 次
想象一个包含 50 个 URL 的列表,跨越 5 个页面,您需要点击 next 按钮才能在页面上移动。
前两个步骤工作正常,但我认为问题在于 nextLink 在循环再次运行之前没有更新。基本上发生的情况是第四步重复使用原始 URL 而不是“新” URL。上述步骤都在一个 if 循环中。
我尝试过使用setTimeout、async...await,因为我认为问题在于它没有时间在下一个功能完成之前加载“新”URL,但确实如此不工作。
如果我在 if 函数中添加console.log(URL),它将打印原始 URL。但是当我将console.log 添加到 if 循环之外时,它会打印更新后的 URL,这让我认为 'nextLink' 直到 if 循环之后才会更新。
我也尝试过一遍又一遍地重复这些函数(本质上是一个重复的 if 语句),但这似乎也没有在下一个函数运行之前更新“nextLink”,这与上述情况背道而驰。
let nextLink = www.source.com/1
//this pulls source page and scrapes required URLs
const getDatafromPage = () => {
request(nextLink, (error, response, html) => {
if((!error) && (response.statusCode == 200))
{
let $ = cheerio.load(html);
$('.class1').each((i, el) => {
let link = $(el).find('.class2').attr('href');
console.log(`${link});
})
}
})
}
//this gets the next URL
const getNextLink = () => {
request(nextLink, (error, response, html) => {
if((!error) && (response.statusCode == 200))
{
let $ = cheerio.load(html);
nextLink = $('.class3').attr('href');
}
})
}
for (let i = 0; i <= 4; i++) {
getDatafromPage();
getNextLink();
}
console.log(nextLink)
预期结果(来自页面的所有 50 个 URL,并以记录最后一个源 URL 结束)
www.urllookingfor.com/1
...
www.urllookingfor.com/50
www.source.com/5
实际结果(重复第一页,但在最后记录下一页):
www.urllookingfor.com/1
...
www.urllookingfor.com/10
www.urllookingfor.com/1
...
www.urllookingfor.com/10
www.source.com/2
【问题讨论】:
-
看起来像是 RxJS 的用例 (github.com/ReactiveX/rxjs)
标签: javascript node.js express cheerio