【问题标题】:How can I get 1 array contains many object to create a JSON file from my code?如何让 1 个数组包含许多对象以从我的代码创建 JSON 文件?
【发布时间】:2021-12-31 10:15:42
【问题描述】:

我有这个网站,我想从中抓取数据。

从第 1 页开始,包含 30 个项目,第 2 页,30 个项目,依此类推,直到最后一页。

我想要什么(它将包含来自许多页面的所有数据):

[
  // All push go into 1 array
  {
  animeURL: "animeURL",
  animeTitle: "animeTitle"
  },
  {
  animeURL: "animeURL",
  animeTitle: "animeTitle"
  },
  ...
]

从我的代码中,我已经成功地得到了我想要的东西,但问题是我猜由于不同的推送,它被许多数组分开了。

我在 console.log 中得到了什么:

// Array from the first push match with first loop
    [
      {
      animeURL: "animeURL",
      animeTitle: "animeTitle"
      },
      {
      animeURL: "animeURL",
      animeTitle: "animeTitle"
      },
    ]
// Array from the first push + second push match with second loop.
    [
      {
      animeURL: "animeURL",
      animeTitle: "animeTitle"
      },
      {
      animeURL: "animeURL",
      animeTitle: "animeTitle"
      },
    ]
// ... array from page 3, 4, 5, 6, ...

这是我的代码:

const PORT = 8000
const axios = require('axios')
const cheerio = require('cheerio')
const express = require('express')
const app = express()



function fetchAnimeData() {
    let animeData = []
    for (i = 1; i<3; i++){
        let url = `https://animehay.club/loc-phim/W1tdLFtdLFtdLFtdXQ==/trang-${i}.html`;
        axios(url)
        .then(response =>{
            const html = response.data
            const $ = cheerio.load(html, {xmlMode: true})
    
            $('.movie-item', html).each(function(){
                const animeUrl = $(this).find('a').attr('href')
                const animeTitle = $(this).find('a').attr('title')
                animeData.push({
                  animeUrl, animeTitle
                })
            })
            console.log(animeData)
        }).catch(err => console.log(err))
    }
 
}

fetchAnimeData()

app.listen(PORT, ()=> {console.log(`Server is running on PORT: ${PORT}`)})

我尝试移动animeData 变量或让它成为全局变量和console.log,有些只得到[],有些会像我发生的问题一样保持不变,我该如何控制台。记录并打印出我想要的结果,即只有 1 个数组包含多页数据?

【问题讨论】:

    标签: javascript web-scraping cheerio


    【解决方案1】:

    你应该跟踪你的承诺:

    let jobs = []
    

    在每个循环中

    jobs.push(axios(url) ...etc )
    

    最后你等待所有工作都解决:

    Promise.all(jobs).then(()=>{
        console.log(animeData);
    })
    

    Promise.all

    【讨论】:

    • 谢谢,这解决了我的问题,我已经被困了半天了。
    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 2020-09-03
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多