簡體   English   中英

如何讓 1 個數組包含許多 object 以從我的代碼創建 JSON 文件?

[英]How can I get 1 array contains many object to create a JSON file from my code?

我有這個網站,我想從中抓取數據。

從第 1 頁開始,包含 30 個項目,第 2 頁,30 個項目,依此類推,直到最后一頁。

我想要什么(它將包含來自許多頁面的所有數據):

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

從我的代碼中,我成功地得到了我想要的東西,但問題是它被許多 arrays 分開,因為我猜是不同的推動。

我在 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,有些只得到[],有些會像我發生的問題一樣保持不變,我怎樣才能console.log並打印出我想要的結果,即只有 1 個數組包含許多頁面數據?

您應該跟蹤您的承諾:

let jobs = []

並且在每個循環中

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

最后,您等待所有工作都解決:

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

Promise.all

function Array.prototype.flat()可用於展平陣列。

 let data = [ [{ animeURL: "animeURL", animeTitle: "animeTitle" }, { animeURL: "animeURL", animeTitle: "animeTitle" } ], [{ animeURL: "animeURL", animeTitle: "animeTitle" }, { animeURL: "animeURL", animeTitle: "animeTitle" } ] ]; console.log(data.flat());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM