【问题标题】:How to use a loop to request a URL, scrape data, grab a new URL from that page and move on to the next page X times如何使用循环请求 URL、抓取数据、从该页面获取新 URL 并移动到下一页 X 次
【发布时间】:2019-05-06 16:09:56
【问题描述】:

我期待:

  1. 打开一个已知的 URL (www.source.com/1 below)
  2. 抓取该页面上的所有 URL (e.g. www.urllookingfor.com/1 to .../10) 并登录到控制台
  3. 从该页面抓取一个新的 URL (e.g. www.source.com/2)
  4. 加载下一页并重复该过程 X 次

想象一个包含 50 个 URL 的列表,跨越 5 个页面,您需要点击 next 按钮才能在页面上移动。

前两个步骤工作正常,但我认为问题在于 nextLink 在循环再次运行之前没有更新。基本上发生的情况是第四步重复使用原始 URL 而不是“新” URL。上述步骤都在一个 if 循环中。

我尝试过使用setTimeoutasync...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

【问题讨论】:

标签: javascript node.js express cheerio


【解决方案1】:

这或多或少是我这样做时的样子:

const doPage = async ($) => {
  // do stuff here
}

;(async function(){
  let response = await request(url)
  let $ = cheerio.load(response)
  await doPage($)
  let a
  // keep following next links
  while(a = $('[rel=next]')[0]){
    url = new URL($(a).attr('href'), url).href 
    response = await request(url)
    $ = cheerio.load(response)
    await doPage($)
  }
})()

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2019-08-22
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多