Files
cuotibiye/collector/xianyu.mjs
T

281 lines
10 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
// 闲鱼采集器:搜关键词,把商品卡片抓下来,标出「弃用信号」。
//
// 为什么抓闲鱼:一个东西被转卖,说明有人买完就放弃了——这比「我想要」诚实得多。
// 错题打印机在闲鱼上大量「吃灰转让」,就是「家长买了但没用起来」最硬的证据。
//
// 用法:
// node collector/xianyu.mjs login
// node collector/xianyu.mjs run --keywords 错题打印机,错题本 --max 40
// node collector/xianyu.mjs selftest
//
// 反爬说明:闲鱼 web 的接口有 mtop 签名,我们不碰它,只读渲染出来的 DOM。
import fs from 'node:fs';
import path from 'node:path';
import { ensureBrowser, attach, navigate, evaluate, sleep } from './cdp.mjs';
const ROOT = process.cwd();
const SEARCH_URL = (kw) => `https://www.goofish.com/search?q=${encodeURIComponent(kw)}`;
// 「买了没用 / 正在脱手」的信号词。命中越多,越说明这个需求是伪需求或体验断层。
const ABANDON_WORDS = [
'吃灰', '闲置', '全新未拆', '未拆封', '买了没用', '用了几次', '用了两次', '就用过',
'不常用', '孩子不用', '不用了', '低价出', '清仓', '转卖', '毕业出', '回血', '半价',
'出闲置', '腾地方', '智商税', '后悔', '用不上', '放着', '九成新', '几乎全新',
];
const num = (v) => {
if (v === null || v === undefined || v === '') return 0;
if (typeof v === 'number') return v;
const m = String(v).replace(/,/g, '').match(/([\d.]+)\s*(万|w|W|k|K)?/);
if (!m) return 0;
const base = parseFloat(m[1]);
const u = m[2];
if (u === '万' || u === 'w' || u === 'W') return Math.round(base * 10000);
if (u === 'k' || u === 'K') return Math.round(base * 1000);
return Math.round(base);
};
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 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;
}
async function shutdown(cdp, launch) {
if (launch && !launch.reused) await cdp.send('Browser.close').catch(() => {});
cdp.close();
}
async function isLoggedIn(cdp) {
const r = await cdp.send('Network.getCookies', { urls: ['https://www.goofish.com'] }).catch(() => ({ cookies: [] }));
const names = new Set((r.cookies || []).map((c) => c.name));
return names.has('cookie2') || names.has('unb') || names.has('_m_h5_tk');
}
/** 从页面 DOM 里抠商品卡片。闲鱼的 class 名是哈希过的,所以按结构 + 文本特征找。 */
async function scrapeCards(cdp) {
const js = `(() => {
const anchors = [...document.querySelectorAll('a[href*="item"]')];
const out = [];
const seen = new Set();
for (const a of anchors) {
const href = a.href || '';
const m = href.match(/[?&]id=(\\d+)/);
if (!m) continue;
const id = m[1];
if (seen.has(id)) continue;
const text = (a.innerText || '').replace(/\\u00a0/g, ' ').trim();
if (text.length < 6) continue;
seen.add(id);
out.push({ item_id: id, url: href, text: text.slice(0, 600) });
}
return out;
})()`;
return evaluate(cdp, js).catch(() => []);
}
function parseCard(card, keyword) {
const lines = card.text
.split(/\n|\r/)
.map((s) => s.trim())
.filter(Boolean);
// 标题:第一行通常就是;如果第一行是「X人想要」之类,往后找
let title = '';
for (const line of lines) {
if (/^(\d+(\.\d+)?万?)?\s*人?想要$/.test(line)) continue;
if (/^[¥¥]/.test(line)) continue;
if (line.length >= 4) {
title = line;
break;
}
}
const priceM = card.text.match(/[¥¥]\s*([\d.]+)/);
const wantM = card.text.match(/([\d.]+万?)\s*人想要/);
const hits = ABANDON_WORDS.filter((w) => card.text.includes(w));
return {
type: 'xy_item',
item_id: card.item_id,
keyword,
title: title.slice(0, 120),
price: priceM ? parseFloat(priceM[1]) : 0,
want_count: wantM ? num(wantM[1]) : 0,
abandon_hits: hits.join('|'),
abandon_count: hits.length,
url: card.url,
text: card.text,
};
}
async function scrollPage(cdp, rounds) {
for (let i = 0; i < rounds; i++) {
await evaluate(cdp, 'window.scrollBy(0, document.documentElement.clientHeight * 0.9); true').catch(() => {});
await sleep(1200);
}
}
async function detectRisk(cdp) {
const text = await evaluate(cdp, 'document.body ? document.body.innerText.slice(0, 3000) : ""').catch(() => '');
if (/验证码|滑块|访问频繁|请稍后再试|登录后查看/.test(text)) {
return text.match(/验证码|滑块|访问频繁|请稍后再试|登录后查看/)[0];
}
return '';
}
async function withBrowser(opts, fn) {
const launch = await ensureBrowser({
port: opts.port,
profileDir: opts.profile,
headless: !!opts.headless,
startUrl: 'https://www.goofish.com',
});
const { cdp } = await attach(opts.port);
try {
return await fn(cdp, launch);
} finally {
await shutdown(cdp, launch);
}
}
function summarize(rows) {
if (!rows.length) return;
const withAbandon = rows.filter((r) => r.abandon_count > 0);
const prices = rows.map((r) => r.price).filter((p) => p > 0).sort((a, b) => a - b);
const median = prices.length ? prices[Math.floor(prices.length / 2)] : 0;
console.log('\n—— 汇总 ——');
console.log(`商品 ${rows.length} 条,其中带「弃用信号」的 ${withAbandon.length} 条(${((withAbandon.length / rows.length) * 100).toFixed(1)}%)`);
console.log(`价格中位数 ¥${median}(区间 ¥${prices[0] || 0} – ¥${prices[prices.length - 1] || 0})`);
const words = {};
for (const r of withAbandon) for (const w of r.abandon_hits.split('|').filter(Boolean)) words[w] = (words[w] || 0) + 1;
const top = Object.entries(words).sort((a, b) => b[1] - a[1]).slice(0, 8);
if (top.length) console.log('高频弃用词:' + top.map(([w, n]) => `${w}(${n})`).join(' '));
console.log('\n弃用信号最强的 5 条:');
for (const r of [...withAbandon].sort((a, b) => b.abandon_count - a.abandon_count).slice(0, 5)) {
console.log(` [${r.abandon_hits}] ¥${r.price} ${r.title.slice(0, 40)}`);
}
}
async function cmdRun(opts) {
return withBrowser(opts, async (cdp) => {
if (!(await isLoggedIn(cdp))) console.warn('警告:没检测到闲鱼登录态,可能只看到部分结果。先跑 login。');
const rows = [];
for (const kw of opts.keywords) {
console.log(`\n=== 关键词:${kw} ===`);
await navigate(cdp, SEARCH_URL(kw));
const risk = await detectRisk(cdp);
if (risk) console.warn(` ! 命中提示「${risk}」,可能需要登录或稍后再试`);
await scrollPage(cdp, opts.rounds);
const cards = await scrapeCards(cdp);
const mine = cards.slice(0, opts.max).map((c) => parseCard(c, kw));
console.log(` 抓到 ${mine.length} 条`);
rows.push(...mine);
await sleep(opts.delay);
}
if (!rows.length) {
console.log('\n没抓到商品。常见原因:没登录 / 触发验证 / 页面结构变了。');
console.log('先跑 node collector/xianyu.mjs login,登录后再跑。');
return;
}
// 按 item_id 去重
const uniq = new Map();
for (const r of rows) uniq.set(r.item_id, r);
const list = [...uniq.values()];
fs.mkdirSync(opts.out, { recursive: true });
const file = path.join(opts.out, `xy_search_${ts()}.jsonl`);
fs.writeFileSync(file, list.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
console.log(`\n已写入 ${file}(${list.length} 条)`);
summarize(list);
});
}
async function cmdLogin(opts) {
return withBrowser({ ...opts, headless: false }, async (cdp) => {
await navigate(cdp, 'https://www.goofish.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}` : '没检测到登录 cookie,可能没登录成功');
});
}
async function cmdSelftest(opts) {
return withBrowser({ ...opts, headless: true }, async (cdp) => {
const v = await evaluate(cdp, '3*3').catch(() => null);
console.log(`selftest: 3*3=${v}`);
console.log('等于 9 说明浏览器 + CDP 正常;闲鱼能不能抓到取决于登录态和页面结构。');
});
}
const HELP = `
闲鱼采集器(弃用信号)
node collector/xianyu.mjs login
node collector/xianyu.mjs run --keywords 错题打印机,错题本 --max 40
参数:
--keywords 逗号分隔,可多个
--max 每个关键词最多取多少条(默认 40)
--rounds 滚动次数,越多加载越多(默认 5)
--delay 关键词之间间隔毫秒(默认 2500)
--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 || 40),
rounds: Number(a.rounds || 5),
delay: Number(a.delay || 2500),
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 === 'run') {
if (!opts.keywords.length) {
console.error('缺 --keywords,例如 --keywords 错题打印机,错题本');
process.exit(1);
}
return cmdRun(opts);
}
console.log(HELP);
}
main().catch((e) => {
console.error('出错:', e.message);
process.exit(1);
});