feat(route): 小红书 用户笔记 全文 (#12330)

* fix(route): 小红书 用户笔记(全文抓取)

* fixed package.json's semver prefix character

* fixed conditions for user page response

* fixed timed out issue when getting full text

* removed the capability to get full text

* added full text feature for notes

* added filter for unnecessary resources requested

* Switched to a concise way to get JSON from HTML

* to bypass the null checked warning from DeepScan

* added note full text to cache

* added more readable error messages

* moved full text feature under a new parameter

* Update maintainer format

* Refactor the error message typing

* Refactor the error message typing

* Refactor error message typing

* Refactor the usage of `tryGet` for expire time

* Close the user page earlier to release resouces

---------
This commit is contained in:
Hower He
2023-05-15 22:14:55 +08:00
committed by GitHub
parent 816d29de46
commit d0d3b6b870
5 changed files with 148 additions and 2 deletions
+5 -1
View File
@@ -1600,7 +1600,11 @@ rule
### 用户笔记
<Route author="lotosbin" example="/xiaohongshu/user/593032945e87e77791e03696/notes" path="/xiaohongshu/user/:user_id/notes" :paramsDesc="['用户 ID']" puppeteer="1" anticrawler="1" radar="1" rssbud="1"/>
<Route author="lotosbin" example="/xiaohongshu/user/593032945e87e77791e03696/notes" path="/xiaohongshu/user/:user_id/notes/:fulltext?" :paramsDesc="['用户 ID', '若为`fulltext`将抓取笔记全文,若为空则只抓取笔记标题']" puppeteer="1" anticrawler="1" radar="1" rssbud="1"/>
::: tip 提示
笔记全文不支持显示视频
:::
### 用户收藏
+1 -1
View File
@@ -1,5 +1,5 @@
module.exports = {
'/board/:board_id': ['lotosbin'],
'/user/:user_id/collect': ['lotosbin'],
'/user/:user_id/notes': ['lotosbin'],
'/user/:user_id/notes/:fulltext?': ['lotosbin', 'howerhe'],
};
+16
View File
@@ -0,0 +1,16 @@
const { getNotes, formatText, formatNote } = require('./util');
module.exports = async (ctx) => {
const userId = ctx.params.user_id;
const url = `https://www.xiaohongshu.com/user/profile/${userId}`;
const { user, notes } = await getNotes(url, ctx.cache);
ctx.state.data = {
title: `${user.nickname} - 笔记 • 小红书 / RED`,
description: formatText(user.desc),
image: user.imageb || user.images,
link: url,
item: notes.map((item) => formatNote(url, item)),
};
};
+1
View File
@@ -1,4 +1,5 @@
module.exports = (router) => {
router.get('/board/:board_id', require('./board'));
router.get('/user/:user_id/notes/fulltext', require('./notes'));
router.get('/user/:user_id/:category', require('./user'));
};
+125
View File
@@ -1,5 +1,6 @@
const config = require('@/config').value;
const logger = require('@/utils/logger');
const { parseDate } = require('@/utils/parse-date');
const getUser = (url, cache) =>
cache.tryGet(
@@ -68,7 +69,131 @@ const getBoard = (url, cache) =>
false
);
const getNotes = (url, cache) =>
cache.tryGet(
url + '/notes', // To avoid mixing with the cache for `user.js`
async () => {
let user = '';
let notes = [];
const setPageFilter = async (page) => {
await page.setRequestInterception(true);
page.on('request', (req) => {
req.resourceType() === 'document' || req.resourceType() === 'script' || req.resourceType() === 'xhr' || req.resourceType() === 'other' ? req.continue() : req.abort();
});
};
const browser = await require('@/utils/puppeteer')({ stealth: true });
try {
const page = await browser.newPage();
await setPageFilter(page);
logger.debug(`Requesting ${url}`);
await page.goto(url);
let otherInfo = {};
let userPosted = {};
try {
[otherInfo, userPosted] = await Promise.all(
['/api/sns/web/v1/user/otherinfo', '/api/sns/web/v1/user_posted'].map((p) =>
page
.waitForResponse((res) => {
const req = res.request();
return req.url().includes(p) && req.method() === 'GET';
})
.then((r) => r.json())
)
);
} catch (e) {
throw Error(`Could not get user information and note list\n${e}`);
}
await page.close();
// Get full text for each note
const notesPromise = userPosted.data.notes.map((n) => {
const noteUrl = url + '/' + n.note_id;
return cache.tryGet(
noteUrl,
async () => {
const notePage = await browser.newPage();
await setPageFilter(notePage);
logger.debug(`Requesting ${noteUrl}`);
await notePage.goto(noteUrl);
let feed = {};
try {
feed = await notePage.evaluate(() => window.__INITIAL_STATE__);
// Sometimes the page is not server-side rendered
if (typeof feed?.note?.note === 'undefined' || JSON.stringify(feed?.note?.note) === '{}') {
const res = await notePage.waitForResponse((res) => {
const req = res.request();
return req.url().includes('/api/sns/web/v1/feed') && req.method() === 'POST';
});
const json = await res.json();
const note_card = json.data.items[0].note_card;
feed.note.note = {
title: note_card.title,
noteId: note_card.id,
desc: note_card.desc,
tagList: note_card.tag_list,
imageList: note_card.image_list,
user: note_card.user,
time: note_card.time,
lastUpdateTime: note_card.last_update_time,
};
}
} catch (e) {
throw Error(`Could not get note ${n.note_id}\n${e}`);
}
await notePage.close();
if (typeof feed?.note?.note !== 'undefined' && JSON.stringify(feed?.note?.note) !== '{}') {
return feed.note.note;
} else {
throw Error(`Could not get note ${n.note_id}`);
}
}
);
});
user = otherInfo.data.basic_info;
notes = await Promise.all(notesPromise);
} finally {
await browser.close();
}
return { user, notes };
},
config.cache.routeExpire,
false
);
const formatText = (text) => text.replace(/(\r\n|\r|\n)/g, '<br>').replace(/\t/g, '&emsp;');
// tag_list.id has nothing to do with its url
const formatTagList = (tagList) => tagList.reduce((acc, item) => acc + `#${item.name} `, ``);
const formatImageList = (imageList) => imageList.reduce((acc, item) => acc + `<img src="${item.url}"><br>`, ``);
const formatNote = (url, note) => ({
title: note.title,
link: url + '/' + note.noteId,
description: formatText(note.desc) + '<br><br>' + formatTagList(note.tagList) + '<br><br>' + formatImageList(note.imageList),
author: note.user.nickname,
pubDate: parseDate(note.time, 'x'),
updated: parseDate(note.lastUpdateTime, 'x'),
});
module.exports = {
getUser,
getBoard,
getNotes,
formatText,
formatNote,
};