[英]Scraping multiple websites with the same theme
const PORT = 5000;
import express from "express";
import axios from "axios";
import cheerio from "cheerio";
const app = express();
const tomsHardware = "https://www.tomshardware.com/best-picks/best-gaming-mouse";
const pcGamer = "https://www.pcgamer.com/the-best-gaming-mouse/";
const requestOne = axios.get(tomsHardware);
const requestTwo = axios.get(pcGamer);
const mice = []
app.get('/', (req, res) => {
res.json('Welcome to my climate change API!');
});
app.get('/mouse', (req, res) => {
axios.all([requestOne, requestTwo])
.then((response) => {
const html = response.data;
const $ = cheerio.load(html);
$('.product__title').each(function (index, elem) {
const title = $(this).text();
mice.push({
title
});
});
res.json(mice)
}).catch((err) => console.log(err));
});
我正在嘗試抓取這兩個網站的論文,但我得到“對象不可迭代”的信息,我也不太確定是否抓取它們,因為它們使用的主題與出現的主題相同,並且使用相同的 class 名稱。
您的response
實際上是兩個響應的數組,因此您需要遍歷該數組並分別解析每個響應的 HTML:
app.get('/mouse', (req, res) => {
axios.all([requestOne, requestTwo])
.then(responses => {
for (const response of responses) {
const html = response.data;
const $ = cheerio.load(html);
$('.product__title').each(function () {
mice.push({title: $(this)text()});
});
}
res.json(mice);
})
.catch(err => console.log(err));
});
請注意, const mice = []
是在處理程序外部聲明的,因此在每次請求時,該數組將隨着重復的元素不斷增長。 您可能希望將它移到請求處理程序閉包中,以便在每次請求時重建它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.