【发布时间】: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