Files

380 lines
13 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
// 小红书数据采集 CLI(CDP 嗅探版)
//
// node collector/cli.mjs login
// node collector/cli.mjs search --keywords "错题本,错题打印机" --max 80
// node collector/cli.mjs notes --max 25
// node collector/cli.mjs run --keywords "错题本" --max 60 --notes 20
// node collector/cli.mjs selftest
//
// 原理:启动一个独立的 Chrome(带自己的 profile,登录一次即可),
// 让页面自己发请求,我们通过 CDP 把它的 JSON 响应存下来。
// 不逆向签名、不伪造请求头,尽量贴近"正常人浏览"。
import fs from 'node:fs';
import path from 'node:path';
import readline from 'node:readline/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
sleep,
ensureBrowser,
attach,
navigate,
evaluate,
currentUrl,
NetSniffer,
} from './cdp.mjs';
import { harvestCards, harvestDetails, harvestComments } from './harvest.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
// ---------- 参数 ----------
function parseArgs(argv) {
const out = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a.startsWith('--')) {
const key = a.slice(2);
const next = argv[i + 1];
if (next === undefined || next.startsWith('--')) out[key] = true;
else {
out[key] = next;
i++;
}
} else out._.push(a);
}
return out;
}
const args = parseArgs(process.argv.slice(2));
const cmd = args._[0] || 'help';
const opts = {
port: Number(args.port || 9222),
profile: path.resolve(ROOT, args.profile || 'data/profile'),
out: path.resolve(ROOT, args.out || 'data/raw'),
headless: !!args.headless,
max: Number(args.max || 60),
notes: Number(args.notes || 20),
delay: Number(args.delay || 4000),
rounds: Number(args.rounds || 40),
comments: Number(args.comments || 0), // 0 = 不额外滚评论
keywords: String(args.keywords || '错题本'),
file: args.file ? path.resolve(ROOT, args.file) : null,
};
fs.mkdirSync(opts.out, { recursive: true });
fs.mkdirSync(opts.profile, { recursive: true });
const now = () => new Date().toISOString();
const log = (...a) => console.log(`[${now().slice(11, 19)}]`, ...a);
const rand = (min, max) => min + Math.random() * (max - min);
const safeName = (s) => s.replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40);
function outFile(prefix) {
const ts = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);
return path.join(opts.out, `${prefix}_${ts}.jsonl`);
}
function appendJsonl(file, records) {
if (!records.length) return;
fs.appendFileSync(file, records.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
}
async function ask(question) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
try {
await rl.question(question);
} finally {
rl.close();
}
}
// ---------- 页面内脚本 ----------
const SCROLL_SEARCH = `(() => {
const se = document.scrollingElement || document.documentElement;
se.scrollTop = se.scrollHeight;
window.scrollTo(0, se.scrollHeight);
return se.scrollHeight;
})()`;
const SCROLL_NOTE = `(() => {
const nodes = [...document.querySelectorAll('div,section,main')];
let n = 0;
for (const d of nodes) {
const cls = String(d.className || '');
if (!/comment|note-scroller|scroll-container|feeds/i.test(cls)) continue;
if (d.scrollHeight > d.clientHeight + 100) { d.scrollTop = d.scrollHeight; n++; }
}
const se = document.scrollingElement || document.documentElement;
se.scrollTop = se.scrollHeight;
return n;
})()`;
const PAGE_TEXT = `(() => (document.body && document.body.innerText || '').slice(0, 300))()`;
async function checkBlocked(cdp) {
const url = await currentUrl(cdp);
if (/captcha|verify|login/i.test(url) && !/search_result|explore|discovery/i.test(url)) {
return `页面跳到了 ${url}`;
}
const text = await evaluate(cdp, PAGE_TEXT).catch(() => '');
if (/验证码|安全验证|访问频繁|请完成验证/.test(text)) return '页面出现验证码/访问频繁提示';
return null;
}
async function guard(cdp, hint) {
const blocked = await checkBlocked(cdp);
if (!blocked) return;
log(`⚠️ 被拦了:${blocked}`);
log(` ${hint}`);
if (args.yes) throw new Error('被风控拦截(--yes 模式不等待人工处理)');
await ask(' 在打开的浏览器里手动处理完,然后按回车继续…');
}
// ---------- 命令 ----------
async function cmdLogin() {
log('启动独立浏览器,登录态会保存在:', opts.profile);
const launch = await ensureBrowser({
port: opts.port,
profileDir: opts.profile,
headless: false,
startUrl: 'https://www.xiaohongshu.com',
});
if (launch.reused) log(`端口 ${opts.port} 上已有浏览器在跑,直接用那个。`);
log('浏览器已打开。请在窗口里扫码登录小红书。');
log('登录完成后回到这里按回车,脚本会关闭浏览器(登录态已落盘)。');
if (!args.yes) await ask('按回车结束…');
const { cdp } = await attach(opts.port);
await shutdown(cdp, launch);
log('完成。');
}
async function doSearch(cdp, sniffer, keyword) {
const url =
'https://www.xiaohongshu.com/search_result?keyword=' +
encodeURIComponent(keyword) +
'&source=web_search_result_notes&type=51';
log(`搜索「${keyword}」`);
sniffer.reset();
await navigate(cdp, url);
await guard(cdp, '可能需要重新登录或稍后再试');
await sleep(rand(1200, 2200));
let best = [];
let stable = 0;
for (let round = 0; round < opts.rounds; round++) {
const cards = harvestCards(sniffer.dump((b) => /search|feed/i.test(b.url)));
if (cards.length > best.length) best = cards;
if (best.length >= opts.max) {
log(` 已拿到 ${best.length} 条,达到上限`);
break;
}
const before = best.length;
await evaluate(cdp, SCROLL_SEARCH).catch(() => {});
await sleep(rand(1600, 2600));
const after = harvestCards(sniffer.dump((b) => /search|feed/i.test(b.url))).length;
stable = after > before ? 0 : stable + 1;
if (stable >= 4) {
log(` 连续 4 轮没有新增,停在第 ${after} 条`);
break;
}
if (round % 5 === 4) log(` …已 ${after} 条`);
}
// 兜底:接口没抄到,就从 DOM 抓卡片
if (best.length === 0) {
log(' 接口没捕到数据,改用 DOM 兜底');
best = await evaluate(
cdp,
`(() => [...document.querySelectorAll('section.note-item, .note-item')].map(el => {
const a = el.querySelector('a[href*="/explore/"], a[href*="/search_result/"]');
const href = a ? a.href : '';
const id = (href.match(/\\/(?:explore|search_result)\\/([0-9a-f]{24})/) || [])[1] || '';
const token = (href.match(/xsec_token=([^&]+)/) || [])[1] || '';
const t = el.innerText.split('\\n').filter(Boolean);
return { note_id: id, xsec_token: token, title: t[0] || '', author_name: t[1] || '' };
}).filter(x => x.note_id))()`
).catch(() => []);
}
return best.slice(0, opts.max).map((c) => ({ type: 'note_card', keyword, ...c }));
}
async function doNote(cdp, sniffer, card) {
const url = `https://www.xiaohongshu.com/explore/${card.note_id}` +
(card.xsec_token ? `?xsec_token=${encodeURIComponent(card.xsec_token)}&xsec_source=pc_search` : '');
sniffer.reset();
await navigate(cdp, url, { timeout: 40000 }).catch(() => {});
await sleep(rand(1500, 2500));
await guard(cdp, '可能需要重新登录或稍后再试');
// 滚一滚,把评论和"展开更多"触发出来
for (let i = 0; i < Math.max(2, opts.comments ? 10 : 2); i++) {
await evaluate(cdp, SCROLL_NOTE).catch(() => {});
await sleep(rand(900, 1500));
}
const detail = harvestDetails(sniffer.dump())[0] || null;
const comments = harvestComments(sniffer.dump());
const records = [];
if (detail) records.push({ type: 'note_detail', keyword: card.keyword, ...detail });
if (comments.length) {
records.push(
...comments.map((c) => ({ type: 'comment', keyword: card.keyword, note_title: card.title, ...c }))
);
}
return { records, detail, comments };
}
function readCardsFromFile(file) {
const text = fs.readFileSync(file, 'utf8');
return text
.split(/\r?\n/)
.filter(Boolean)
.map((l) => {
try {
return JSON.parse(l);
} catch {
return null;
}
})
.filter((r) => r && r.note_id);
}
// 只关闭"本次自己启动"的浏览器;如果连的是你已经开着的实例,就不动它
async function shutdown(cdp, launch) {
try {
if (launch && !launch.reused) await cdp.send('Browser.close').catch(() => {});
} finally {
cdp.close();
}
}
async function cmdSearch() {
const launch = await ensureBrowser({ port: opts.port, profileDir: opts.profile, headless: opts.headless });
const { cdp } = await attach(opts.port);
const sniffer = new NetSniffer(cdp);
await sniffer.enable();
const kws = opts.keywords.split(/[,,]/).map((s) => s.trim()).filter(Boolean);
const file = outFile('search');
let total = 0;
for (const kw of kws) {
const cards = await doSearch(cdp, sniffer, kw);
appendJsonl(file, cards);
total += cards.length;
log(`「${kw}」拿到 ${cards.length} 条`);
await sleep(rand(3000, 6000));
}
log(`共 ${total} 条 → ${file}`);
await shutdown(cdp, launch);
}
async function cmdNotes() {
const files = opts.file
? [opts.file]
: fs.readdirSync(opts.out).filter((f) => f.startsWith('search_') && f.endsWith('.jsonl')).map((f) => path.join(opts.out, f));
if (!files.length) throw new Error('没有找到 search_*.jsonl,先跑 search');
const seen = new Map();
for (const f of files) for (const c of readCardsFromFile(f)) if (!seen.has(c.note_id)) seen.set(c.note_id, c);
const cards = [...seen.values()].slice(0, opts.notes);
log(`准备抓 ${cards.length} 篇笔记的详情和评论`);
const launch = await ensureBrowser({ port: opts.port, profileDir: opts.profile, headless: opts.headless });
const { cdp } = await attach(opts.port);
const sniffer = new NetSniffer(cdp);
await sniffer.enable();
const file = outFile('note');
let nNotes = 0;
let nComments = 0;
for (let i = 0; i < cards.length; i++) {
const card = cards[i];
log(`[${i + 1}/${cards.length}] ${(card.title || card.note_id).slice(0, 30)}`);
try {
const { records, detail, comments } = await doNote(cdp, sniffer, card);
if (detail) nNotes++;
nComments += comments.length;
appendJsonl(file, records);
log(` 详情${detail ? '✓' : '✗'} 评论 ${comments.length}`);
} catch (e) {
log(` 失败:${e.message}`);
}
await sleep(rand(opts.delay * 0.7, opts.delay * 1.4));
}
log(`完成:${nNotes} 篇详情 / ${nComments} 条评论 → ${file}`);
await shutdown(cdp, launch);
}
async function cmdRun() {
await cmdSearch();
if (args['no-notes']) return;
await cmdNotes();
}
async function cmdSelftest() {
const html = path.join(opts.out, '_selftest.html');
fs.writeFileSync(html, '<!doctype html><title>selftest-ok</title><h1>hello</h1>', 'utf8');
const launch = await ensureBrowser({
port: opts.port,
profileDir: opts.profile,
headless: true,
startUrl: 'about:blank',
});
const { cdp } = await attach(opts.port);
try {
await navigate(cdp, pathToFileURL(html).href);
const title = await evaluate(cdp, 'document.title');
const one = await evaluate(cdp, '1+1');
log(`title=${title} 1+1=${one}`);
if (title !== 'selftest-ok') throw new Error('selftest 失败:拿不到页面标题');
log('selftest 通过:CDP 连接、导航、页面求值都正常');
} finally {
await shutdown(cdp, launch);
fs.rmSync(html, { force: true });
}
}
function help() {
console.log(`小红书采集器
node collector/cli.mjs login 扫码登录(登录态存到 data/profile)
node collector/cli.mjs search --keywords "错题本" --max 80
node collector/cli.mjs notes --max 25 抓详情 + 评论
node collector/cli.mjs run --keywords "错题本,错题打印机" --max 60 --notes 20
node collector/cli.mjs selftest 不开浏览器界面,自检
可选参数:
--port 9222 调试端口
--headless 无头模式(更容易被风控,默认关闭)
--delay 4000 每篇笔记之间的间隔毫秒
--comments 1 是否多滚几轮加载评论
--yes 不等待人工确认
`);
}
const commands = {
login: cmdLogin,
search: cmdSearch,
notes: cmdNotes,
run: cmdRun,
selftest: cmdSelftest,
help,
};
const fn = commands[cmd] || help;
try {
await fn();
} catch (e) {
console.error('❌', e.message);
process.exitCode = 1;
}