Files
cuotibiye/collector/douyin.mjs
T

343 lines
13 KiB
JavaScript
Raw 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
// 抖音 Web 采集器:按关键词搜视频,再逐条打开抓评论。
//
// 思路和小红书采集器一样:不逆向签名,让真实的、已登录的 Chrome 自己去请求,
// 我们在旁边用 CDP 把 /aweme/v1/web/ 的 JSON 响应抄下来。
//
// 用法:
// node collector/douyin.mjs login // 打开抖音,扫码登录(只需一次)
// node collector/douyin.mjs search --keywords 错题本 --max 10
// node collector/douyin.mjs run --keywords 错题本,错题打印机 --max 8 --videos 5
// node collector/douyin.mjs selftest
//
// 前置:Node 22+、本机 Chrome;沙箱环境需要 danger-full-access(Chrome 起不来)。
import fs from 'node:fs';
import path from 'node:path';
import { ensureBrowser, attach, navigate, evaluate, sleep, NetSniffer, walk } from './cdp.mjs';
const ROOT = process.cwd();
const SEARCH_URL = (kw) => `https://www.douyin.com/search/${encodeURIComponent(kw)}?type=video`;
const VIDEO_URL = (id) => `https://www.douyin.com/video/${id}`;
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 num = (v) => {
if (v === null || v === undefined || v === '') return 0;
if (typeof v === 'number') return v;
const s = String(v).replace(/,/g, '').trim();
const m = s.match(/^([\d.]+)\s*(万|w|W|k|K|亿)?/);
if (!m) return 0;
const base = parseFloat(m[1]);
const unit = m[2];
if (!unit) return Math.round(base);
if (unit === '万' || unit === 'w' || unit === 'W') return Math.round(base * 10000);
if (unit === '亿') return Math.round(base * 100000000);
return Math.round(base * 1000);
};
const ts = () => {
const d = new Date();
const p = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
};
function writeJsonl(rows, outDir, prefix) {
fs.mkdirSync(outDir, { recursive: true });
const file = path.join(outDir, `${prefix}_${ts()}.jsonl`);
fs.writeFileSync(file, rows.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
return file;
}
async function shutdown(cdp, launch) {
if (launch && !launch.reused) await cdp.send('Browser.close').catch(() => {});
cdp.close();
}
async function detectRisk(cdp) {
const text = await evaluate(cdp, 'document.body ? document.body.innerText.slice(0, 4000) : ""').catch(() => '');
if (/验证码|滑块|访问过于频繁|操作频繁|安全验证/.test(text)) return text.match(/验证码|滑块|访问过于频繁|操作频繁|安全验证/)[0];
return '';
}
async function isLoggedIn(cdp) {
const cookies = await cdp.send('Network.getCookies', { urls: ['https://www.douyin.com'] }).catch(() => ({ cookies: [] }));
const names = new Set((cookies.cookies || []).map((c) => c.name));
return names.has('sessionid') || names.has('sessionid_ss') || names.has('sid_tt');
}
/** 从嗅到的 JSON 里认视频对象:有 aweme_id 和 desc,通常还带 statistics */
export function harvestVideos(bodies) {
const seen = new Map();
for (const { json } of bodies) {
walk(json, (o) => {
const id = o.aweme_id || o.awemeId;
if (!id || !o.desc) return;
const st = o.statistics || o.stats || {};
const author = o.author || {};
const cur = seen.get(String(id)) || { type: 'dy_video', video_id: String(id) };
cur.desc = String(o.desc || cur.desc || '').replace(/\s+/g, ' ').trim();
cur.author_name = author.nickname || cur.author_name || '';
cur.author_id = author.sec_uid || author.uid || cur.author_id || '';
cur.digg_count = Math.max(num(st.digg_count), num(cur.digg_count));
cur.comment_count = Math.max(num(st.comment_count), num(cur.comment_count));
cur.share_count = Math.max(num(st.share_count), num(cur.share_count));
cur.collect_count = Math.max(num(st.collect_count), num(cur.collect_count));
cur.create_time = o.create_time || cur.create_time || 0;
cur.duration = num(o.duration) || cur.duration || 0;
cur.url = `https://www.douyin.com/video/${id}`;
seen.set(String(id), cur);
});
}
return [...seen.values()];
}
/** 认评论:有 cid + text,还会带 digg_count / reply_comment_total */
export function harvestDyComments(bodies, videoId) {
const seen = new Map();
for (const { json } of bodies) {
walk(json, (o) => {
const cid = o.cid;
if (!cid || !o.text) return;
const user = o.user || {};
const cur = seen.get(String(cid)) || { type: 'dy_comment', comment_id: String(cid) };
cur.video_id = String(videoId || o.aweme_id || '');
cur.user_name = user.nickname || cur.user_name || '';
cur.user_id = user.uid || user.sec_uid || cur.user_id || '';
cur.content = String(o.text || '').replace(/\s+/g, ' ').trim();
cur.like_count = Math.max(num(o.digg_count), num(cur.like_count));
cur.reply_count = Math.max(num(o.reply_comment_total), num(cur.reply_count));
cur.ip_label = o.ip_label || cur.ip_label || '';
cur.create_time = o.create_time || cur.create_time || 0;
cur.parent_id = o.reply_id || cur.parent_id || '';
seen.set(String(cid), cur);
});
}
return [...seen.values()];
}
/** DOM 兜底:接口被拦或改了字段时,直接从页面读评论文字 */
async function domComments(cdp) {
const js = `(() => {
const nodes = [...document.querySelectorAll('[data-e2e="comment-item"], div[class*="comment-item"]')];
return nodes.slice(0, 200).map((n, i) => ({
comment_id: 'dom_' + i,
content: (n.innerText || '').replace(/\\s+/g, ' ').slice(0, 500),
})).filter((x) => x.content.length > 1);
})()`;
return evaluate(cdp, js).catch(() => []);
}
async function scrollComments(cdp, rounds) {
for (let i = 0; i < rounds; i++) {
await evaluate(cdp, `(() => {
const box = document.querySelector('[data-e2e="comment-list"], div[class*="comment-list"]');
if (box) box.scrollBy(0, 1200);
window.scrollBy(0, 900);
return true;
})()`).catch(() => {});
await sleep(1200);
}
}
async function withBrowser(opts, fn) {
const launch = await ensureBrowser({
port: opts.port,
profileDir: opts.profile,
headless: !!opts.headless,
startUrl: 'https://www.douyin.com',
});
const { cdp } = await attach(opts.port);
try {
return await fn(cdp, launch);
} finally {
await shutdown(cdp, launch);
}
}
async function cmdLogin(opts) {
await withBrowser({ ...opts, headless: false }, async (cdp) => {
await navigate(cdp, 'https://www.douyin.com');
console.log('浏览器已打开抖音,请扫码登录。登录完成后按回车继续(这个窗口不会自动关)。');
await new Promise((resolve) => {
process.stdin.resume();
process.stdin.once('data', () => {
process.stdin.pause();
resolve();
});
});
console.log((await isLoggedIn(cdp)) ? '已检测到登录态,profile 已保存到 ' + opts.profile : '没检测到 sessionid,登录可能没成功');
});
}
async function searchOnce(cdp, sniffer, keyword, max, scrollRounds) {
sniffer.reset();
await navigate(cdp, SEARCH_URL(keyword));
const risk = await detectRisk(cdp);
if (risk) console.warn(` ! 命中风控提示「${risk}」,建议手动处理后再跑`);
for (let i = 0; i < scrollRounds; i++) {
await evaluate(cdp, 'window.scrollBy(0, 1200)').catch(() => {});
await sleep(1000);
}
await sleep(800);
const videos = harvestVideos(sniffer.dump()).slice(0, max);
for (const v of videos) v.keyword = keyword;
return videos;
}
async function commentsOnce(cdp, sniffer, video, scrollRounds) {
sniffer.reset();
await navigate(cdp, video.url);
await sleep(1500);
const risk = await detectRisk(cdp);
if (risk) console.warn(` ! 命中风控提示「${risk}」`);
await scrollComments(cdp, scrollRounds);
await sleep(800);
let rows = harvestDyComments(sniffer.dump(), video.video_id);
if (!rows.length) {
const dom = await domComments(cdp);
rows = dom.map((d) => ({
type: 'dy_comment',
comment_id: d.comment_id,
video_id: video.video_id,
content: d.content,
source: 'dom',
}));
}
for (const r of rows) {
r.keyword = video.keyword || '';
r.video_desc = video.desc || '';
}
return rows;
}
async function cmdSearch(opts) {
return withBrowser(opts, async (cdp) => {
if (!(await isLoggedIn(cdp))) console.warn('警告:没检测到抖音登录态,搜索结果可能为空。先跑 login。');
const sniffer = new NetSniffer(cdp, { urlIncludes: '/aweme/v1/web/' });
await sniffer.enable();
const all = [];
for (const kw of opts.keywords) {
console.log(`\n=== 关键词:${kw} ===`);
const videos = await searchOnce(cdp, sniffer, kw, opts.max, opts.rounds);
console.log(` 拿到视频 ${videos.length} 条`);
all.push(...videos);
}
if (!all.length) {
console.log('\n没拿到数据。常见原因:没登录 / 触发验证码 / 页面结构变了。');
return;
}
const file = writeJsonl(all, opts.out, 'dy_search');
console.log(`\n已写入 ${file}(${all.length} 条)`);
});
}
async function cmdRun(opts) {
return withBrowser(opts, async (cdp) => {
if (!(await isLoggedIn(cdp))) console.warn('警告:没检测到抖音登录态。先跑 login。');
const sniffer = new NetSniffer(cdp, { urlIncludes: '/aweme/v1/web/' });
await sniffer.enable();
const videos = [];
const comments = [];
for (const kw of opts.keywords) {
console.log(`\n=== 关键词:${kw} ===`);
const found = await searchOnce(cdp, sniffer, kw, opts.max, opts.rounds);
console.log(` 视频 ${found.length} 条`);
videos.push(...found);
const targets = found.slice(0, opts.videos);
for (const v of targets) {
const rows = await commentsOnce(cdp, sniffer, v, opts.commentRounds);
console.log(` · ${v.desc.slice(0, 28)} → 评论 ${rows.length} 条`);
comments.push(...rows);
await sleep(opts.delay);
}
}
if (!videos.length) {
console.log('\n没拿到数据:没登录 / 验证码 / 结构变化。先跑 node collector/douyin.mjs login');
return;
}
const f1 = writeJsonl(videos, opts.out, 'dy_search');
const f2 = comments.length ? writeJsonl(comments, opts.out, 'dy_note') : '';
console.log(`\n已写入视频 ${videos.length} 条 → ${f1}`);
if (f2) console.log(`已写入评论 ${comments.length} 条 → ${f2}`);
});
}
async function cmdSelftest(opts) {
return withBrowser({ ...opts, headless: true }, async (cdp) => {
const v = await evaluate(cdp, '2+2').catch(() => null);
console.log(`selftest: 2+2=${v}`);
console.log('如果上面是 4,说明浏览器 + CDP 链路正常;抖音数据能不能拿到取决于登录态。');
});
}
const HELP = `
抖音 Web 采集器
node collector/douyin.mjs login
node collector/douyin.mjs search --keywords 错题本 --max 10
node collector/douyin.mjs run --keywords 错题本,错题打印机 --max 8 --videos 5
参数:
--keywords 逗号分隔,可多个
--max 每个关键词最多取多少条视频(默认 10)
--videos 每个关键词打开几条视频抓评论(默认 3)
--rounds 搜索页滚动次数(默认 4)
--comment-rounds 视频页滚动次数(默认 5)
--delay 视频之间的间隔毫秒(默认 3000)
--out 输出目录(默认 data/raw)
--profile Chrome 用户目录(默认 data/profile)
--port CDP 端口(默认 9222)
--headless 无头模式(抖音建议不用,容易触发风控)
`;
async function main() {
const argv = process.argv.slice(2);
const cmd = argv[0] || 'help';
const a = parseArgs(argv.slice(1));
const opts = {
keywords: a.keywords ? String(a.keywords).split(',').map((s) => s.trim()).filter(Boolean) : [],
max: Number(a.max || 10),
videos: Number(a.videos || 3),
rounds: Number(a.rounds || 4),
commentRounds: Number(a['comment-rounds'] || 5),
delay: Number(a.delay || 3000),
out: a.out || path.join(ROOT, 'data/raw'),
profile: a.profile || path.join(ROOT, 'data/profile'),
port: Number(a.port || 9222),
headless: !!a.headless,
};
if (cmd === 'help' || cmd === '--help') return console.log(HELP);
if (cmd === 'selftest') return cmdSelftest(opts);
if (cmd === 'login') return cmdLogin(opts);
if (cmd === 'search' || cmd === 'run') {
if (!opts.keywords.length) {
console.error('缺 --keywords,例如 --keywords 错题本,错题打印机');
process.exit(1);
}
return cmd === 'search' ? cmdSearch(opts) : cmdRun(opts);
}
console.log(HELP);
}
main().catch((e) => {
console.error('出错:', e.message);
process.exit(1);
});