我有這個網站,我想從中抓取資料。
從第 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,有些只會得到[],有些會像我遇到的問題一樣保持不變,我如何console.log并列印出結果我想要的,只有 1 個陣列包含多頁資料?
uj5u.com熱心網友回復:
你應該跟蹤你的承諾:
let jobs = []
并且在每個回圈中
jobs.push(axios(url) ...etc )
最后你等待所有的作業都解決了:
Promise.all(jobs).then(()=>{
console.log(animeData);
})
承諾.all
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401179.html
標籤:javascript 网页抓取 啦啦队
