下面是一个使用Node.js、Express和Axios实现的简单爬虫效果
下面这个示例代码根据中国日报网站的HTML结构来提取文章标题和链接。实际上,网站结构可能会发生变化,因此您需要根据实际情况调整选择器。
const express = require("express");
const axios = require("axios");
const cheerio = require("cheerio");
const app = express();
app.get("/", async (req, res) => {
const url = "https://cn.chinadaily.com.cn/"; // 比如中国日报网址
try {
const response = await axios.get(url);
const $ = cheerio.load(response.data);
// 根据页面结构选择合适的选择器,这里只是一个例子,实际情况可能不同
const articles = $("div.Home_content_Item_Text");
const articleData = [];
articles.each((index, element) => {
const title = $(element).find("h1 > a").text().trim();
const link = $(element).find("h1 > a").attr("href");
const content = $(element).find("h2 > a").text().trim();
articleData.push({ title, content ,link });
});
console.log(articleData);
res.send(articleData);
} catch (error) {
console.error(error);
res.status(500).send("Error fetching data");
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
在运行此代码之前,请确保安装了cheerio
、express
和axios
这三个NPM包。您可以通过以下命令安装它们:
npm install express axios cheerio
然后,将上述代码保存为app.js
,并在命令行中运行node app.js
。应用程序将在端口3000上启动。通过访问http://localhost:3000
,您可以看到获取的文章列表,并在控制台中查看打印出的数据。