1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
|
(function () { 'use strict';
if (!/(^|\.)xiaohongshu\.com$|(^|\.)rednote\.com$/.test(location.hostname)) { alert('请在小某书网页版 www.xiaohongshu.com 的页面里运行本脚本。'); return; } if (window.__XHS_UNFOLLOW_ACTIVE__) { console.warn('[批量取关] 面板已经在运行了,请勿重复粘贴。'); return; } window.__XHS_UNFOLLOW_ACTIVE__ = true;
const CFG = { dryRun: true, intervalMs: 900, jitterMs: 600, coolEvery: 100, coolMs: 30000, maxRounds: 40, whitelist: [], mode: 'api', };
const S = { running: false, paused: false, stopped: false, done: new Map(), fail: new Map(), logs: [], preview: [], };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const wait = () => sleep(CFG.intervalMs + Math.random() * CFG.jitterMs); const now = () => new Date().toLocaleTimeString('zh-CN', { hour12: false });
function log(msg) { const line = `[${now()}] ${msg}`; S.logs.push(line); if (S.logs.length > 2000) S.logs.shift(); console.log('%c[批量取关]', 'color:#ff2442', msg); const box = UI && UI.logBox; if (box) { box.textContent = S.logs.slice(-300).join('\n'); box.scrollTop = box.scrollHeight; } updateUI(); }
function walk(obj, cb, depth) { if (!obj || typeof obj !== 'object' || (depth || 0) > 6) return; for (const k of Object.keys(obj)) { let v; try { v = obj[k]; } catch (e) { continue; } cb(k, v); if (v && typeof v === 'object') walk(v, cb, (depth || 0) + 1); } }
function extractUser(item) { let id = null, name = '', anyId = null; walk(item, (k, v) => { if (typeof v !== 'string') return; if (/^(target_)?(user_?)?id$|^(target_)?user_id$/i.test(k) && /^[0-9a-f]{24}$/i.test(v)) { if (!id) id = v; } if (!name && /^(nickname|nick_name|display_name|user_name|username|name|title)$/i.test(k)) { const t = v.trim(); if (t && t.length <= 50) name = t; } if (!anyId && /^[0-9a-f]{24}$/i.test(v)) anyId = v; }); id = id || anyId; return id ? { id: id, name: name || ('用户…' + id.slice(-6)) } : null; }
function dedupe(list) { const m = new Map(); for (const u of list) if (u && u.id && !m.has(u.id)) m.set(u.id, u); return [...m.values()]; }
function isProtected(u) { if (!CFG.whitelist.length) return false; const hay = (u.name + ' ' + u.id).toLowerCase(); return CFG.whitelist.some((w) => w && hay.indexOf(w.toLowerCase()) !== -1); }
function parseWhitelist(text) { return String(text || '').split(/[,,\s;;]+/).map((s) => s.trim()).filter(Boolean); }
function findSignFn() { for (const n of ['_webmsxyw', 'webmsxyw', '_webmsxyw_', 'xhsSign', 'xhs_sign']) { if (typeof window[n] === 'function') return window[n]; } for (const k of Object.getOwnPropertyNames(window)) { if (/webms|msxyw/i.test(k) && typeof window[k] === 'function') return window[k]; } return null; }
function signHeaders(path, body) { const fn = findSignFn(); if (!fn) { const e = new Error('NO_SIGN_FN'); e.fatal = true; throw e; } let out; try { out = fn(path, body === undefined ? {} : body); } catch (e) { out = fn(path, body); } if (!out || typeof out !== 'object') { const e = new Error('BAD_SIGN'); e.fatal = true; throw e; } const h = {}; for (const k of Object.keys(out)) { const lk = k.toLowerCase().replace(/[_-]/g, ''); if (lk === 'xs') h['X-s'] = String(out[k]); else if (lk === 'xt') h['X-t'] = String(out[k]); else if (/^x[-_]/i.test(k)) h[k] = String(out[k]); } if (!h['X-s'] && !h['X-t']) { const e = new Error('EMPTY_SIGN'); e.fatal = true; throw e; } return h; }
function isRisk(e, json) { const status = e && e.status; if ([403, 406, 429, 461, 471, 472].indexOf(status) !== -1) return true; const text = JSON.stringify(json || (e && e.json) || {}); return /验证码|安全验证|操作频繁|操作太频繁|访问频繁|请稍后再试|行为异常|存在风险|账号异常|captcha|risk_control|too many requests|rate limit/i.test(text); }
const BASES = ['', 'https://edith.xiaohongshu.com'];
async function request(path, method, body) { let lastErr = null; for (const base of BASES) { try { const headers = Object.assign( { Accept: 'application/json, text/plain, */*' }, signHeaders(path, body) ); if (body !== undefined) headers['Content-Type'] = 'application/json;charset=UTF-8'; const res = await fetch(base + path, { method: method, credentials: 'include', headers: headers, body: body === undefined ? undefined : JSON.stringify(body), }); let json = null; try { json = await res.json(); } catch (e) { } if (!res.ok) { const e = new Error('HTTP ' + res.status + (json && json.msg ? ' · ' + json.msg : '')); e.status = res.status; e.json = json; throw e; } if (json && typeof json.code === 'number' && json.code !== 0) { const e = new Error('接口 code=' + json.code + (json.msg ? ' · ' + json.msg : '')); e.json = json; throw e; } return json; } catch (e) { lastErr = e; if (e.fatal || isRisk(e)) throw e; } } throw lastErr || new Error('请求失败'); }
const LIST_PATHS = [ '/api/sns/web/v1/intimacy/intimacy_list', '/api/sns/web/v1/user/follow/page?num=100&cursor=', ];
async function fetchFollowing() { let lastErr = null; for (const p of LIST_PATHS) { try { const json = await request(p, 'GET'); const d = (json && json.data) || {}; const items = d.items || d.list || d.users || d.user_list || d.follows || (Array.isArray(d) ? d : null) || (Array.isArray(json && json.items) ? json.items : null); if (!Array.isArray(items)) { lastErr = new Error('列表结构未识别:' + p); continue; } return dedupe(items.map(extractUser).filter(Boolean)); } catch (e) { lastErr = e; if (e.fatal || isRisk(e)) throw e; } } throw lastErr || new Error('拉取关注列表失败'); }
function unfollow(id) { return request('/api/sns/web/v1/user/unfollow', 'POST', { target_user_id: id }); } function follow(id) { return request('/api/sns/web/v1/user/follow', 'POST', { target_user_id: id }); }
function domCards() { const links = [...document.querySelectorAll('a[href*="/user/profile/"]')]; const out = new Map(); for (const a of links) { const m = (a.getAttribute('href') || '').match(/\/user\/profile\/([0-9a-f]{24})/i); if (!m) continue; let card = a, btn = null, depth = 0; while (card && depth < 6) { const cands = [...card.querySelectorAll('button, [role="button"], div, span, a')] .filter((el) => /^(已关注|取消关注)$/.test((el.textContent || '').trim())); if (cands.length) { btn = cands[cands.length - 1]; break; } card = card.parentElement; depth++; } if (!btn) continue; const nick = (card && (card.textContent || '').trim().split('\n')[0]) || ''; if (!out.has(m[1])) out.set(m[1], { id: m[1], name: nick.slice(0, 30) || ('用户…' + m[1].slice(-6)), btn: btn }); } return [...out.values()]; }
async function domClick(btn) { btn.scrollIntoView({ block: 'center' }); btn.click(); await sleep(350); const confirms = [...document.querySelectorAll('button, [role="button"], div, span')] .filter((el) => { const t = (el.textContent || '').trim(); return /^(确定|确认|取消关注)$/.test(t) && el.offsetParent !== null; }); if (confirms.length) confirms[confirms.length - 1].click(); await sleep(300); }
async function run() { if (S.running) { log('已经在运行中。'); return; } S.running = true; S.paused = false; S.stopped = false; syncCfgFromUI(); log(CFG.dryRun ? '=== 模拟运行(不会改动账号)===' : '=== 正式执行:开始取关 ==='); try { if (CFG.mode === 'dom') { await runDom(); return; } if (CFG.dryRun) { const list = await fetchFollowing(); S.preview = list; const keep = list.filter(isProtected); log('读到 ' + list.length + ' 个关注对象' + (keep.length ? ',其中 ' + keep.length + ' 个被白名单保护' : '') + '。'); log('接口单次最多返回约 450 人;正式运行时会反复「拉取 → 取关 → 再拉取」,直到列表清空。'); list.slice(0, 25).forEach((u) => log(' · ' + u.name + ' (' + u.id + ')' + (isProtected(u) ? ' [保留]' : ''))); if (list.length > 25) log(' … 其余 ' + (list.length - 25) + ' 人省略,可点「导出日志」查看完整名单'); log('确认无误后:取消勾选「模拟运行」,再点「开始」。'); return; } let round = 0, total = 0, consecFail = 0; while (!S.stopped && round < CFG.maxRounds) { round++; const list = await fetchFollowing(); const targets = list.filter((u) => !isProtected(u) && !S.done.has(u.id) && !S.fail.has(u.id)); const skipped = list.length - targets.length; if (!targets.length) { log('第 ' + round + ' 轮:没有待处理对象(已清空,或剩余 ' + skipped + ' 个为白名单/失败项)。'); break; } log('第 ' + round + ' 轮:读到 ' + list.length + ' 人,本轮待取关 ' + targets.length + ' 人'); for (const u of targets) { if (S.stopped) break; while (S.paused && !S.stopped) await sleep(300); if (S.stopped) break; try { await unfollow(u.id); S.done.set(u.id, Object.assign({}, u, { at: Date.now() })); total++; consecFail = 0; log('✓ 已取关 ' + u.name + ' (' + u.id + ') [累计 ' + total + ']'); if (CFG.coolEvery > 0 && total % CFG.coolEvery === 0) { log('⏸ 已处理 ' + total + ' 人,冷却 ' + Math.round(CFG.coolMs / 1000) + ' 秒降低风控风险…'); await sleep(CFG.coolMs); } } catch (e) { if (isRisk(e)) { log('⛔ 命中风控信号,已紧急停止。请间隔 10~30 分钟再试,并把间隔调大。'); S.stopped = true; break; } consecFail++; S.fail.set(u.id, Object.assign({}, u, { err: String(e.message || e) })); log('✗ 失败 ' + u.name + ':' + (e.message || e)); if (consecFail >= 5) { log('连续 5 次失败,已停止以避免异常。可点「诊断」排查。'); S.stopped = true; break; } } await wait(); } if (S.stopped) break; await sleep(1200); } log('=== 结束:成功取关 ' + total + ' 人,失败 ' + S.fail.size + ' 人 ==='); if (S.fail.size) log('失败名单已记录,可点「导出日志」保存,或「撤销」回滚成功的部分。'); } catch (e) { log('运行中断:' + (e && e.message ? e.message : String(e))); if (e && e.fatal) { log('找不到页面签名函数。请:① 确认已登录;② 刷新页面后重新粘贴脚本;③ 或把「模式」切到「页面点击」并先打开关注列表弹窗。'); } else if (isRisk(e)) { log('⛔ 疑似风控或登录态失效,已停止。请稍后再试。'); } } finally { S.running = false; updateUI(); } }
async function runDom() { log('页面点击模式:请确保已打开「关注」列表弹窗,并滚动到能看到用户卡片。'); const cards = domCards().filter((u) => !isProtected(u) && !S.done.has(u.id)); if (!cards.length) { log('没有识别到带「已关注」按钮的用户卡片。请确认关注列表弹窗已打开且已滚动加载。'); return; } log('识别到 ' + cards.length + ' 个可操作对象。' + (CFG.dryRun ? '(模拟运行,仅列出)' : '')); cards.slice(0, 15).forEach((u) => log(' · ' + u.name + ' (' + u.id + ')')); if (CFG.dryRun) return; if (!confirm('将对识别到的 ' + cards.length + ' 个对象逐个点击「已关注」取关,确定继续?')) return; let total = 0; for (const u of cards) { if (S.stopped) break; while (S.paused && !S.stopped) await sleep(300); try { await domClick(u.btn); S.done.set(u.id, { id: u.id, name: u.name, at: Date.now() }); total++; log('✓ 已点击取关 ' + u.name + ' [累计 ' + total + ']'); if (CFG.coolEvery > 0 && total % CFG.coolEvery === 0) { log('⏸ 冷却 ' + Math.round(CFG.coolMs / 1000) + ' 秒…'); await sleep(CFG.coolMs); } } catch (e) { S.fail.set(u.id, { id: u.id, name: u.name, err: String(e.message || e) }); log('✗ 失败 ' + u.name + ':' + (e.message || e)); } await wait(); } log('=== 本轮结束:' + total + ' 个。列表会随取关变化,可再点一次「开始」继续,或先手动滚动加载。==='); }
async function undo() { const list = [...S.done.values()]; if (!list.length) { log('本次会话没有可撤销的记录。'); return; } if (S.running) { log('请先停止当前任务再撤销。'); return; } if (!confirm('将重新关注本次已取关的 ' + list.length + ' 人。\n\n注意:对方可能收到关注通知,且短时间内大量关注同样会触发风控,不保证完全恢复。\n确定继续?')) return; S.running = true; S.stopped = false; log('开始撤销 ' + list.length + ' 人…'); let ok = 0; for (const u of list) { if (S.stopped) break; try { await follow(u.id); S.done.delete(u.id); ok++; log('↩ 已重新关注 ' + u.name); } catch (e) { if (isRisk(e)) { log('⛔ 撤销时命中风控,已停止。'); break; } log('✗ 撤销失败 ' + u.name + ':' + (e.message || e)); } await wait(); } log('撤销完成:' + ok + ' / ' + list.length + ' 人。'); S.running = false; updateUI(); }
function exportLog() { const data = { exportedAt: new Date().toISOString(), config: Object.assign({}, CFG), success: [...S.done.values()], failed: [...S.fail.values()], preview: S.preview, logs: S.logs, }; const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'xhs-unfollow-' + new Date().toISOString().replace(/[:.]/g, '-') + '.json'; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 5000); log('已导出日志(含完整名单)。'); }
function diagnose() { log('--- 诊断 ---'); log('当前地址:' + location.href); log('签名函数 window._webmsxyw:' + (findSignFn() ? '✅ 可用' : '❌ 未找到(可改用「页面点击」模式)')); log('登录 Cookie a1:' + (/(?:^|;\s*)a1=/.test(document.cookie) ? '✅ 存在' : '❌ 未检测到,可能未登录')); log('当前页面识别到的「已关注」卡片:' + domCards().length + ' 个'); log('本次成功 / 失败:' + S.done.size + ' / ' + S.fail.size); log('------------'); }
const host = document.createElement('div'); host.style.cssText = 'position:fixed;top:16px;right:16px;z-index:2147483647;'; document.body.appendChild(host); const root = host.attachShadow({ mode: 'open' }); root.innerHTML = ` <style> :host { all: initial; } * { box-sizing: border-box; } .panel { width: 372px; max-height: 86vh; display: flex; flex-direction: column; background: #fff; color: #1f2329; border: 1px solid #e5e6eb; border-radius: 14px; box-shadow: 0 12px 40px rgba(0,0,0,.18); font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif; overflow: hidden; } .hd { display:flex; align-items:center; justify-content:space-between; padding:12px 14px; background:#ff2442; color:#fff; font-weight:600; font-size:14px; } .hd span { cursor:pointer; font-size:18px; line-height:1; opacity:.85; } .bd { padding:12px 14px; overflow:auto; } .stat { background:#f7f8fa; border-radius:8px; padding:8px 10px; margin-bottom:10px; font-size:12px; color:#4e5969; } .stat b { color:#ff2442; font-size:14px; } .row { display:flex; align-items:center; gap:8px; margin-bottom:8px; } .row label { width:64px; flex:none; color:#4e5969; font-size:12px; } input[type=text], input[type=number], select { flex:1; min-width:0; padding:6px 8px; border:1px solid #dcdfe6; border-radius:6px; font-size:12px; color:#1f2329; background:#fff; outline:none; } input:focus, select:focus { border-color:#ff2442; } .row.two input { width:50%; } .chk { display:flex; align-items:center; gap:6px; margin:2px 0 10px; font-size:12px; color:#1f2329; } .chk input { accent-color:#ff2442; } .warn { background:#fff7e6; border:1px solid #ffe0a3; color:#8a5a00; padding:7px 9px; border-radius:6px; font-size:11px; margin-bottom:10px; } .btns { display:grid; grid-template-columns:repeat(3,1fr); gap:6px; margin-bottom:10px; } button { padding:7px 4px; border:1px solid #dcdfe6; background:#fff; color:#1f2329; border-radius:6px; font-size:12px; cursor:pointer; } button:hover { border-color:#ff2442; color:#ff2442; } button.primary { background:#ff2442; border-color:#ff2442; color:#fff; font-weight:600; } button.primary:hover { background:#e51f3b; color:#fff; } button.danger { color:#d03050; } button:disabled { opacity:.45; cursor:not-allowed; } .logbox { height:180px; overflow:auto; background:#f7f8fa; border-radius:8px; padding:8px 10px; font:11px/1.6 ui-monospace, Consolas, "Courier New", monospace; color:#4e5969; white-space:pre-wrap; word-break:break-all; } .tip { font-size:11px; color:#86909c; margin-top:8px; } </style> <div class="panel"> <div class="hd">小某书 · 批量取关 <span id="close" title="关闭">×</span></div> <div class="bd"> <div class="stat" id="stat">状态:待机 · 已取关 <b>0</b> · 失败 <b>0</b></div> <div class="warn">默认「模拟运行」只列名单、不改账号。取消勾选后才会真的取关,操作不可逆。</div> <div class="row"><label>白名单</label><input type="text" id="wl" placeholder="保留的昵称/ID 关键词,逗号分隔"></div> <div class="row two"><label>间隔 ms</label><input type="number" id="iv" value="900" min="450" step="100"> <input type="number" id="jt" value="600" min="0" step="100" title="随机抖动 ms"></div> <div class="row two"><label>冷却</label><input type="number" id="ce" value="100" min="0" step="10" title="每 N 次"> <input type="number" id="cm" value="30" min="0" step="5" title="冷却秒数"></div> <div class="row"><label>模式</label><select id="mode"> <option value="api">站点接口(推荐,可全清)</option> <option value="dom">页面点击(备用,需打开关注列表弹窗)</option> </select></div> <label class="chk"><input type="checkbox" id="dry" checked> 模拟运行(不改动账号)</label> <div class="btns"> <button class="primary" id="start">开始</button> <button id="pause">暂停</button> <button class="danger" id="stop">停止</button> <button id="diag">诊断</button> <button id="undo">撤销</button> <button id="export">导出日志</button> </div> <div class="logbox" id="logbox"></div> <div class="tip">保持标签页在前台可见。命中风控会自动熔断;取关不可逆,请先用模拟运行核对名单。</div> </div> </div>`;
const $ = (id) => root.getElementById(id); const UI = { logBox: $('logbox'), stat: $('stat'), wl: $('wl'), iv: $('iv'), jt: $('jt'), ce: $('ce'), cm: $('cm'), mode: $('mode'), dry: $('dry'), start: $('start'), pause: $('pause'), stop: $('stop'), };
function syncCfgFromUI() { CFG.whitelist = parseWhitelist(UI.wl.value); CFG.intervalMs = Math.max(450, Number(UI.iv.value) || 900); CFG.jitterMs = Math.max(0, Number(UI.jt.value) || 0); CFG.coolEvery = Math.max(0, Number(UI.ce.value) || 0); CFG.coolMs = Math.max(0, (Number(UI.cm.value) || 0) * 1000); CFG.mode = UI.mode.value; CFG.dryRun = UI.dry.checked; }
function updateUI() { const state = S.running ? (S.paused ? '暂停中' : '运行中') : '待机'; UI.stat.innerHTML = '状态:' + state + ' · 已取关 <b>' + S.done.size + '</b> · 失败 <b>' + S.fail.size + '</b>'; }
UI.start.addEventListener('click', () => { syncCfgFromUI(); run(); }); UI.pause.addEventListener('click', () => { S.paused = !S.paused; UI.pause.textContent = S.paused ? '继续' : '暂停'; log(S.paused ? '已暂停(当前操作完成后生效)。' : '已继续。'); }); UI.stop.addEventListener('click', () => { S.stopped = true; S.paused = false; UI.pause.textContent = '暂停'; log('收到停止指令…'); }); $('diag').addEventListener('click', diagnose); $('undo').addEventListener('click', undo); $('export').addEventListener('click', exportLog); $('close').addEventListener('click', () => { if (S.running && !confirm('任务还在运行,确定关闭面板?关闭后只能重新粘贴脚本恢复。')) return; host.remove(); window.__XHS_UNFOLLOW_ACTIVE__ = false; });
updateUI(); log('面板已就绪。当前【模拟运行】开启,点「开始」先看看会处理哪些人。'); log('提示:如需保留重要账号,先在「白名单」填昵称关键词。'); window.__XHS_UNFOLLOW__ = { config: CFG, state: S, run: run, undo: undo, diagnose: diagnose, export: exportLog }; })();
|