- 本章使用NodeJS服務(wù)端接口獲取簡書文章列表數(shù)據(jù)轉(zhuǎn)換成JSON返回
查看簡書網(wǎng)站發(fā)現(xiàn)請求文章接口:
http://m.itdecent.cn/u/xxxxx?page=1 // xxxx換成自己的簡書id
原始接口響應(yīng)數(shù)據(jù)為HTML:

原始數(shù)據(jù)
目標(biāo)
通過NodeJS發(fā)送請求獲取文章列表響應(yīng)數(shù)據(jù),解析html成如下JSON數(shù)據(jù)返回:
[{
{
"title": "解決 vite build打包報錯Top-level await is not available in the configured target",
"abstract": "一、錯誤原因最高層中不讓使用 await二、解決方案1.引入vite-plugin-top-level-await 2.在 vite.config...",
"read": "6940",
"time": "2023-03-30 09:55"
},
....
}]
創(chuàng)建工程
項目根目錄文件夾運行如下命令:
npm init //初始化一個新包并生成 package.json 文件
安裝插件
npm i express // Express 是一個保持最小規(guī)模的靈活的 Node.js Web 應(yīng)用程序開發(fā)框架
npm i cheerio // cheerio 是一個專為 Node.js 服務(wù)器環(huán)境設(shè)計的快速、靈活且優(yōu)雅的 HTML 和 XML 解析庫,其 API 設(shè)計借鑒了 jQuery,可以理解成服務(wù)端jQuery
npm i axios // Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
啟動命令
package.json的scripts中添加命令:
scripts: {
"dev": "node index"
}
index.js
/**
* @author: 圓夢
* @desc: 抓取簡述書文章列表信息
*/
// 導(dǎo)入 express 模塊
const express = require('express');
// 導(dǎo)入 cheerio 模塊
const cheerio = require('cheerio');
// 創(chuàng)建請求實例
const app = express();
// 導(dǎo)入 axios 模塊
const axios = require('axios');
// 端口
const port = 3000;
/**
* 格式化日期
* @param {*} dateStr
* @returns
*/
function formatDateTime(dateStr) {
const date = new Date(dateStr);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
// return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
/**
* 默認(rèn)請求
*/
app.get('/', (req, res) => {
res.send('Hello!')
});
/**
* 抓取簡述書文章列表信息
* 服務(wù)端接口: /getList?page=2
*/
app.get('/getList', async (req, res) => {
//
let params = req.query;
// 查詢頁數(shù)
let page = params.page || 1;
// xxxx換成自己的簡書id
let url = `http://m.itdecent.cn/u/xxxx?page=${page}`;
// 發(fā)送請求
const response = await axios.get(url, {
headers: {}
});
//
let data = response.data;
//
let result = [];
// 解析html數(shù)據(jù)
let $ = cheerio.load(data);
let noteListEl = $('.note-list>li>.content');
noteListEl.each(function(index, item) {
let itemEl = $(item);
// 標(biāo)題
let title = itemEl.find('.title').text().trim();
// 摘要
let abstract = itemEl.find('.abstract').text().trim();
// 閱讀數(shù)
let read = itemEl.find('.meta a').eq(0).text().trim();
// 時間
let time = formatDateTime(itemEl.find('.meta .time').attr('data-shared-at'));
//
result.push({
title,
abstract,
read,
time,
});
});
console.log('response.data:', result);
// 響應(yīng)json數(shù)據(jù)
res.json(result);
// 響應(yīng)結(jié)束
res.end();
});
/**
* 監(jiān)聽端口
*/
app.listen(port, () => {
console.log(`服務(wù)啟動成功端口: ${port}`)
});
啟動服務(wù)
使用npm run dev啟動,瀏覽器訪問:http://localhost:3000/getList?page=2
轉(zhuǎn)換成JSON對象返回

解析后結(jié)果