// ==UserScript== // @name 小说下载器 // @name:zh-CN 小说下载器 // @namespace novel-downloader // @version 1.1.0 // @description 识别小说目录页并逐章抓取正文,清理广告后合并导出为 TXT // @description:zh-CN 识别小说目录页并逐章抓取正文,清理广告后合并导出为 TXT // @author local // @license MIT // @match *://*/* // @run-at document-idle // @grant none // @noframes // ==/UserScript== /** * 小说下载器 · 单文件版 v1.1.0 * ------------------------------------------------------------ * 版本:v1.1.0 * * 两种用法: * * 【1】Tampermonkey / 用户脚本(推荐长期使用) * Edge 安装 Tampermonkey 扩展 → 新建脚本 → 粘贴本文件全部内容 → 保存。 * 打开小说页面后,脚本会自动识别并开始抓取,右下角有进度面板。 * 建议把上面的 @match 改成你要用的小说站点(可写多行), * 例如:// @match *://*.example-novel.com/* * 这样脚本只在这些站点运行,不会在别的网站上做任何事。 * * 【2】浏览器控制台(临时用) * 在小说页面按 F12 → 控制台 →(首次需输入 allow pasting)→ * 粘贴本文件全部内容 → 回车。脚本会自动识别并开始抓取, * 完成后自动下载「书名.txt」,右下角有进度面板和取消按钮。 * * 可调参数见下方 CONFIG,改完再保存/粘贴即可生效: * delay 每章之间的等待毫秒数(默认 800,站点慢就调大) * selector 正文容器的 CSS 选择器(留空自动识别) * indent 段落是否加两个全角空格缩进 * startIndex / endIndex 只抓目录中的某一段(endIndex 为 0 表示抓到底) * autoRun 识别到小说页后是否自动开始(false 时手动执行 NovelDL.run()) * * 也可以先 NovelDL.config({ delay: 1500 }); 再 NovelDL.run()。 * 仅用于下载你有权访问、可离线保存的内容。 */ (function () { 'use strict'; const VERSION = '1.1.0'; const CONFIG = { delay: 800, selector: '', indent: true, startIndex: 1, endIndex: 0, maxChapters: 3000, autoRun: true }; /* ========================= 基础工具 ========================= */ function clean(s) { if (!s) return ''; return String(s) .replace(/\u00a0/g, ' ') .replace(/[\r\n\t]+/g, ' ') .replace(/ {2,}/g, ' ') .trim(); } function textLen(el) { return el ? (el.textContent || '').length : 0; } function linkRatio(el) { const total = textLen(el); if (!total) return 1; let linkLen = 0; const as = el.querySelectorAll('a'); for (let i = 0; i < as.length; i++) linkLen += (as[i].textContent || '').length; return Math.min(1, linkLen / total); } function normalizeUrl(u) { try { const x = new URL(u, location.href); x.hash = ''; return x.href; } catch (e) { return u; } } function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); } function log() { const args = Array.prototype.slice.call(arguments); console.log('%c[小说下载器]', 'color:#2563eb;font-weight:bold', ...args); } /* ========================= 噪声行识别 ========================= */ const AD_RES = [ /本站(域名|网址|地址|首发|备用)/, /请记住本站/, /记住本站/, /最快更新/, /更新最快/, /无弹窗/, /最新(章节|网址|书签|列表)/, /百度搜索/, /加入书签/, /手机(版|阅读|用户|站|端)/, /章节(内容)?(错误|有误|报错)/, /求(月票|推荐票|收藏|订阅|打赏)/, /投(月票|推荐票)/, /天才一秒记住/, /一秒记住/, /翻页阅读/, /本章未完/, /点击(下一页|下一章|继续阅读)/, /继续阅读/, /内容(加载中|正在加载)/, /本站所有小说/, /免费(阅读|下载|提供)/, /全集下载/, /^\(?未完待续/, /^https?:\/\//i, /www\.[a-z0-9-]+\.(com|net|org|cc|info|cn|top|vip)/i, /^[\u4e00-\u9fa5]{2,8}(网|书屋|小说网|阅读网|文学网|中文网)$/, /^(上一?章|下一?章|目录|返回目录|章节(目录|列表)|加入书签|投推荐票)+$/, /^[\s\-—=*·_]{4,}$/ ]; function isAd(line) { if (!line) return true; if (line.length > 80) return false; for (let i = 0; i < AD_RES.length; i++) if (AD_RES[i].test(line)) return true; return false; } /* ========================= 正文定位 ========================= */ const CONTENT_SELECTORS = [ '#chaptercontent', '#chapterContent', '#chapter-content', '#content', '#booktxt', '#txtContent', '#htmlContent', '#nr1', '#nr', '#article', '#acontent', '#booktext', '#txtcontent', '#chapter_content', '.read-content', '.article-content', '.novel-content', '.chapter-content', '.showtxt', '.box_con #content', '.content', '.txt' ]; function findContentBlock(doc) { for (let i = 0; i < CONTENT_SELECTORS.length; i++) { let list; try { list = doc.querySelectorAll(CONTENT_SELECTORS[i]); } catch (e) { continue; } for (let j = 0; j < list.length; j++) { const el = list[j]; if (textLen(el) >= 80 && linkRatio(el) < 0.25) return el; } } const body = doc.body || doc.documentElement; if (!body) return null; let cur = body; for (let depth = 0; depth < 10; depth++) { const curLen = textLen(cur); let pick = null; let pickScore = 0; const kids = cur.children; for (let i = 0; i < kids.length; i++) { const kid = kids[i]; if (/^(SCRIPT|STYLE|NOSCRIPT|IFRAME|HEADER|FOOTER|NAV|ASIDE|FORM|SVG)$/.test(kid.tagName)) continue; const len = textLen(kid); if (len < Math.max(150, curLen * 0.55)) continue; const lr = linkRatio(kid); const cjk = (kid.textContent.match(/[\u4e00-\u9fa5]/g) || []).length; const pCount = kid.querySelectorAll('p').length; const score = len * Math.pow(1 - lr, 2) * (0.2 + Math.min(1, cjk / Math.max(1, len))) + pCount * 30; if (score > pickScore) { pickScore = score; pick = kid; } } if (!pick) break; cur = pick; } const parent = cur.parentElement; if (parent && parent !== body) { if (textLen(parent) <= textLen(cur) * 2.2 && linkRatio(parent) < 0.25) return parent; } return cur; } /* ========================= 段落还原 ========================= */ function toLines(block) { const doc = block.ownerDocument; const clone = block.cloneNode(true); clone.querySelectorAll('script,style,noscript,iframe,ins,svg').forEach(function (n) { n.remove(); }); clone.querySelectorAll('br').forEach(function (br) { br.replaceWith(doc.createTextNode('\n')); }); clone.querySelectorAll('p,div,li,tr,h1,h2,h3,h4,section,blockquote,dd,dt').forEach(function (el) { el.append('\n'); }); return (clone.textContent || '').split('\n'); } function mergeLines(lines) { const out = []; const END = /[。!?!?…”’」』))\]]$/; const MIN_LEN = 120; let buf = ''; for (let i = 0; i < lines.length; i++) { const line = lines[i]; buf += line; if ((END.test(line) && buf.length >= MIN_LEN) || buf.length >= 400) { const t = buf.trim(); if (t) out.push(t); buf = ''; } } if (buf.trim()) out.push(buf.trim()); return out; } function extractParagraphs(block) { if (!block) return []; const pCount = block.querySelectorAll('p').length; let lines = toLines(block).map(clean).filter(Boolean).filter(function (l) { return !isAd(l); }); if (!lines.length) return []; const shortRatio = lines.filter(function (l) { return l.length < 26; }).length / lines.length; if (pCount < 4 && lines.length >= 6 && shortRatio > 0.6) lines = mergeLines(lines); return lines; } /* ========================= 章节信息 ========================= */ const CHAPTER_NO_RE = /第\s*([0-9零〇一二三四五六七八九十百千万两]+)\s*[章节節回卷话話篇集部]/; const CN_NUM = { 零: 0, 〇: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 }; function cnToNum(s) { s = String(s).trim(); if (/^\d+$/.test(s)) return parseInt(s, 10); let total = 0, section = 0, num = 0; for (let i = 0; i < s.length; i++) { const ch = s[i]; if (CN_NUM[ch] !== undefined) num = CN_NUM[ch]; else if (ch === '十') { section += (num || 1) * 10; num = 0; } else if (ch === '百') { section += (num || 1) * 100; num = 0; } else if (ch === '千') { section += (num || 1) * 1000; num = 0; } else if (ch === '万') { total += (section + num) * 10000; section = 0; num = 0; } else return null; } return total + section + num; } function chapterNo(title) { const m = CHAPTER_NO_RE.exec(title || ''); if (m) { const n = cnToNum(m[1]); if (n !== null) return n; } const m2 = /^\s*([0-9]{1,4})\s*[、..::]/.exec(title || ''); if (m2) return parseInt(m2[1], 10); return null; } const CHAPTER_MARK = /第\s*[0-9零〇一二三四五六七八九十百千万两]+\s*[章节節回卷话話篇集部]|^\s*[0-9]{1,4}\s*[、..::]|[楔序]子|序章|序言|前言|后记|後記|尾声|尾聲|番外|外传|外傳|大结局|大結局|终章|終章|终篇/; const TITLE_SELECTORS = [ '.bookname h1', '#chaptertitle', '#nr_title', '.chapter-title', '.chapterTitle', '.title', '#title', '.chaptername', '#chaptername', '.bookname', 'h1', 'h2' ]; function chapterTitle(doc) { for (let i = 0; i < TITLE_SELECTORS.length; i++) { let el = null; try { el = doc.querySelector(TITLE_SELECTORS[i]); } catch (e) { continue; } if (!el) continue; const t = clean(el.textContent); if (t && t.length >= 2 && t.length <= 80) return t; } const t = clean(doc.title || ''); return t ? clean(t.split(/[_||]/)[0]) : ''; } const NEXT_RE = /^(下一?章|下一?節|下一?节|下一?页|下一?頁|下章|下一篇|下页)$/; function nextLink(doc, pageUrl) { const as = doc.querySelectorAll('a[href]'); for (let i = 0; i < as.length; i++) { const a = as[i]; const t = clean(a.textContent); if (!NEXT_RE.test(t)) continue; const href = a.getAttribute('href') || ''; if (/^(javascript:|#|mailto:)/i.test(href)) continue; try { const u = new URL(href, pageUrl); if (/^https?:/.test(u.protocol)) return u.href; } catch (e) {} } return ''; } function metaContent(doc, key) { const sels = ['meta[property="' + key + '"]', 'meta[name="' + key + '"]', 'meta[property="og:' + key + '"]']; for (let i = 0; i < sels.length; i++) { let el = null; try { el = doc.querySelector(sels[i]); } catch (e) { continue; } if (el) { const v = clean(el.getAttribute('content') || ''); if (v) return v; } } return ''; } function cleanTitleText(t) { let s = clean(t || ''); if (!s) return ''; s = s.replace(/[-_||::\s]*(最新章节|无弹窗|全文阅读|免费阅读|小说最新章节).*$/, '').trim(); s = s.replace(/[-_||]\s*[^-_||]{2,20}$/, '').trim(); return clean(s); } function bookInfo(doc, pageUrl) { let bookTitle = metaContent(doc, 'og:novel:book_name') || metaContent(doc, 'book_name') || metaContent(doc, 'og:title'); let author = metaContent(doc, 'og:novel:author') || metaContent(doc, 'author'); if (!bookTitle) { const sels = ['.bookname h1', '.book-info h1', '#info h1', '.bookinfo h1', '.bookname', '#bookname', 'h1']; for (let i = 0; i < sels.length; i++) { let el = null; try { el = doc.querySelector(sels[i]); } catch (e) { continue; } if (!el) continue; const t = clean(el.textContent); if (t && t.length >= 1 && t.length <= 40 && chapterNo(t) === null) { bookTitle = t; break; } } } if (!author) { const sels = ['.book-info h3', '#info h3', '.bookinfo h3', '.author', '.book-html .author']; for (let i = 0; i < sels.length; i++) { let el = null; try { el = doc.querySelector(sels[i]); } catch (e) { continue; } if (!el) continue; const t = clean(el.textContent).replace(/^作\s*者[::]\s*/, ''); if (t && t.length <= 30) { author = t; break; } } } if (!bookTitle) bookTitle = cleanTitleText(doc.title || ''); if (!bookTitle) { try { bookTitle = new URL(pageUrl).hostname; } catch (e) { bookTitle = '未命名'; } } return { bookTitle: clean(bookTitle), author: clean(author) }; } /* ========================= 目录解析 ========================= */ function chapterList(doc, pageUrl) { const anchors = doc.querySelectorAll('a[href]'); const raw = []; for (let i = 0; i < anchors.length; i++) { const a = anchors[i]; const href = a.getAttribute('href') || ''; if (!href || /^(javascript:|#|mailto:|tel:)/i.test(href)) continue; const title = clean(a.textContent); if (!title || title.length > 60) continue; if (!CHAPTER_MARK.test(title)) continue; let url; try { url = new URL(href, pageUrl); } catch (e) { continue; } if (!/^https?:/.test(url.protocol)) continue; if (url.href === pageUrl) continue; raw.push({ title: title, url: url.href, parent: a.parentElement, idx: raw.length }); } if (raw.length < 3) return []; const groups = new Map(); for (let i = 0; i < raw.length; i++) { const it = raw[i]; const key = it.parent; if (!key) continue; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(it); } let maxSize = 0; groups.forEach(function (arr) { if (arr.length > maxSize) maxSize = arr.length; }); const picked = []; groups.forEach(function (arr) { if (arr.length >= Math.max(4, Math.floor(maxSize * 0.5))) { for (let i = 0; i < arr.length; i++) picked.push(arr[i]); } }); if (!picked.length) for (let i = 0; i < raw.length; i++) picked.push(raw[i]); picked.sort(function (a, b) { return a.idx - b.idx; }); const seen = new Map(); const out = []; for (let i = 0; i < picked.length; i++) { const it = picked[i]; const key = normalizeUrl(it.url); if (seen.has(key)) { out[seen.get(key)] = it; continue; } seen.set(key, out.length); out.push(it); } return sortChapters(out).map(function (it) { return { title: it.title, url: it.url }; }); } function sortChapters(list) { if (list.length < 3) return list; const keys = list.map(function (it) { const n = chapterNo(it.title); if (n !== null) return n; if (/楔子|序章|序言|前言|引子/.test(it.title)) return -0.5; if (/番外|外传|后记|尾声|大结局|终章|终篇/.test(it.title)) return 1e9; return null; }); const keyed = keys.filter(function (k) { return k !== null; }).length; if (keyed / list.length < 0.7) return list; let desc = 0, asc = 0; for (let i = 1; i < keys.length; i++) { if (keys[i] === null || keys[i - 1] === null) continue; if (keys[i] < keys[i - 1]) desc++; else if (keys[i] > keys[i - 1]) asc++; } let work = list; let k2 = keys; if (desc > asc * 1.5) { work = list.slice().reverse(); k2 = k2.slice().reverse(); } let last = -1; const finalKeys = k2.map(function (k) { if (k === null) { last = last + 0.1; return last; } last = k; return k; }); return work .map(function (it, i) { return { it: it, k: finalKeys[i], i: i }; }) .sort(function (a, b) { return a.k - b.k || a.i - b.i; }) .map(function (x) { return x.it; }); } /* ========================= 页面分析 ========================= */ function analyzePage(doc, pageUrl, selector) { const info = bookInfo(doc, pageUrl); const chapters = chapterList(doc, pageUrl); const isToc = chapters.length >= 3; const chapter = isToc ? null : extractChapterFromDoc(doc, pageUrl, selector); return { pageUrl: pageUrl, bookTitle: info.bookTitle, author: info.author, isToc: isToc, chapters: chapters, chapter: chapter }; } function extractChapterFromDoc(doc, pageUrl, selector) { let block = null; if (selector) { try { block = doc.querySelector(selector); } catch (e) { block = null; } if (block && textLen(block) < 30) block = null; } if (!block) block = findContentBlock(doc); if (!block) return null; let paragraphs = extractParagraphs(block); if (!paragraphs.length) return null; const title = chapterTitle(doc); if (title) { const first = paragraphs[0]; if (first === title) paragraphs = paragraphs.slice(1); else if (first.indexOf(title) === 0 && first.length - title.length <= 24) { const rest = first.slice(title.length).trim(); if (rest) paragraphs[0] = rest; else paragraphs = paragraphs.slice(1); } } if (!paragraphs.length) return null; if (paragraphs.join('').length < 60) return null; return { title: title, paragraphs: paragraphs, charCount: paragraphs.join('').length, nextUrl: nextLink(doc, pageUrl) }; } /* ========================= 抓取单章 ========================= */ function normalizeCharset(cs) { const s = String(cs || '').trim().toLowerCase().replace(/["']/g, ''); if (!s) return 'utf-8'; if (s === 'gb2312' || s === 'gbk' || s === 'x-gbk') return 'gb18030'; if (s === 'utf8') return 'utf-8'; return s; } function decodeHtml(buf, contentType) { const bytes = new Uint8Array(buf); let charset = ''; const m = String(contentType || '').match(/charset\s*=\s*"?([a-zA-Z0-9_\-]+)/i); if (m) charset = m[1]; if (!charset) { let head = ''; try { head = new TextDecoder('utf-8').decode(bytes.subarray(0, Math.min(bytes.length, 8192))); } catch (e) {} const mm = head.match(/]+charset\s*=\s*["']?\s*([a-zA-Z0-9_\-]+)/i); if (mm) charset = mm[1]; } let cs = normalizeCharset(charset); let out; try { out = new TextDecoder(cs).decode(bytes); } catch (e) { out = new TextDecoder('utf-8').decode(bytes); } const sample = out.slice(0, 3000); if (cs === 'utf-8' && /\uFFFD{2,}/.test(sample)) { try { const alt = new TextDecoder('gb18030').decode(bytes); if (!/[\uFFFD]{2,}/.test(alt.slice(0, 3000)) && /[\u4e00-\u9fa5]/.test(alt.slice(0, 3000))) out = alt; } catch (e) {} } else if (cs !== 'utf-8' && /\uFFFD{2,}/.test(sample)) { try { const alt = new TextDecoder('utf-8').decode(bytes); if (!/[\uFFFD]{2,}/.test(alt.slice(0, 3000)) && /[。,!?]/.test(alt.slice(0, 3000)) ) out = alt; } catch (e) {} } return out; } async function fetchChapter(url, selector) { for (let attempt = 0; attempt < 2; attempt++) { const controller = new AbortController(); const timer = setTimeout(function () { controller.abort(); }, 20000); try { const res = await fetch(url, { credentials: 'include', redirect: 'follow', cache: 'no-store', signal: controller.signal, headers: { 'Accept': 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8' } }); clearTimeout(timer); if (!res.ok) { if (attempt === 0 && (res.status === 429 || res.status >= 500)) { await sleep(1200); continue; } throw new Error('HTTP ' + res.status); } const buf = await res.arrayBuffer(); const html = decodeHtml(buf, res.headers.get('content-type') || ''); const doc = new DOMParser().parseFromString(html, 'text/html'); const parsed = extractChapterFromDoc(doc, res.url || url, selector); if (parsed && parsed.paragraphs.length && parsed.charCount >= 20) return parsed; throw new Error('未识别到正文'); } catch (e) { clearTimeout(timer); if (attempt === 0) { await sleep(1000); continue; } return { error: String(e && e.message || e) }; } } return { error: '抓取失败' }; } /* ========================= 进度面板 ========================= */ function createPanel(bookTitle) { const old = document.getElementById('novel-dl-panel'); if (old) old.remove(); const box = document.createElement('div'); box.id = 'novel-dl-panel'; box.style.cssText = [ 'position:fixed', 'right:20px', 'bottom:20px', 'width:300px', 'background:#111827', 'color:#fff', 'border-radius:12px', 'padding:12px 14px', 'font:13px/1.5 -apple-system,"Microsoft YaHei",sans-serif', 'box-shadow:0 10px 30px rgba(0,0,0,.35)', 'z-index:2147483647' ].join(';'); const title = document.createElement('div'); title.style.cssText = 'display:flex;align-items:baseline;gap:6px;margin-bottom:6px;font-weight:600'; const nameEl = document.createElement('span'); nameEl.style.cssText = 'flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis'; nameEl.textContent = bookTitle || '小说下载器'; const verEl = document.createElement('span'); verEl.style.cssText = 'flex:none;font-weight:400;font-size:11px;color:#9ca3af'; verEl.textContent = 'v' + VERSION; title.appendChild(nameEl); title.appendChild(verEl); const bar = document.createElement('div'); bar.style.cssText = 'height:6px;background:#374151;border-radius:4px;overflow:hidden;margin-bottom:6px'; const fill = document.createElement('div'); fill.style.cssText = 'height:100%;width:0;background:linear-gradient(90deg,#3b82f6,#6366f1);transition:width .3s'; bar.appendChild(fill); const text = document.createElement('div'); text.style.cssText = 'font-size:12px;color:#d1d5db'; text.textContent = '准备中…'; const btn = document.createElement('button'); btn.textContent = '取消'; btn.style.cssText = 'margin-top:8px;width:100%;padding:6px;border:none;border-radius:8px;background:#374151;color:#e5e7eb;cursor:pointer;font-size:12px'; box.appendChild(title); box.appendChild(bar); box.appendChild(text); box.appendChild(btn); document.body.appendChild(box); const state = { cancelled: false }; btn.addEventListener('click', function () { state.cancelled = true; btn.textContent = '正在停止…'; btn.disabled = true; }); return { state: state, set: function (msg, percent) { text.textContent = msg; if (typeof percent === 'number') fill.style.width = Math.max(0, Math.min(100, percent)) + '%'; }, done: function (msg) { text.textContent = msg; fill.style.width = '100%'; btn.textContent = '关闭'; btn.disabled = false; btn.onclick = function () { box.remove(); }; }, fail: function (msg) { text.textContent = msg; text.style.color = '#f87171'; fill.style.background = '#dc2626'; btn.textContent = '关闭'; btn.disabled = false; btn.onclick = function () { box.remove(); }; }, remove: function () { box.remove(); } }; } /* ========================= 导出 ========================= */ function sanitizeName(s) { const t = String(s || '未命名') .replace(/[\\/:*?"<>|\r\n\t]/g, '_') .replace(/\s+/g, ' ') .trim() .slice(0, 80); return t || '未命名'; } function pad2(n) { return String(n).length < 2 ? '0' + n : String(n); } function fmtNow() { const d = new Date(); return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes()); } function buildTxt(meta, results, failed) { const indent = meta.indent ? '\u3000\u3000' : ''; const lines = []; lines.push(meta.bookTitle || '未命名'); if (meta.author) lines.push('作者:' + meta.author); if (meta.source) lines.push('来源:' + meta.source); lines.push('抓取时间:' + fmtNow()); lines.push('导出工具:小说下载器 v' + VERSION); lines.push('章节数:' + results.length + (failed ? '(失败 ' + failed + ' 章)' : '')); lines.push(''); lines.push(new Array(31).join('=')); lines.push(''); for (let i = 0; i < results.length; i++) { const r = results[i]; const title = r.title || ('第 ' + (i + 1) + ' 章'); lines.push(title); lines.push(''); for (let j = 0; j < r.paragraphs.length; j++) lines.push(indent + r.paragraphs[j]); lines.push(''); } return lines.join('\r\n'); } function downloadTxt(text, filename) { const blob = new Blob(['\ufeff' + text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(function () { try { URL.revokeObjectURL(url); } catch (e) {} a.remove(); }, 5000); return blob.size; } /* ========================= 主流程 ========================= */ let running = false; let panel = null; async function run(opts) { if (running) { log('已有任务在进行中'); return null; } const cfg = Object.assign({}, CONFIG, opts || {}); if (!cfg.selector) cfg.selector = CONFIG.selector; const page = analyzePage(document, location.href, cfg.selector); log('书名:' + page.bookTitle + (page.author ? ' / 作者:' + page.author : '')); log(page.isToc ? ('识别到目录,共 ' + page.chapters.length + ' 章') : ('识别为正文页:' + ((page.chapter && page.chapter.title) || '未识别到正文'))); if (!page.isToc && !page.chapter) { const msg = '没有识别到章节列表或正文。可在脚本顶部把 selector 设为正文容器的 CSS 选择器后重试。'; log(msg); createPanel('未识别到内容').fail(msg); return { ok: false, error: msg }; } running = true; const results = []; let failed = 0; const meta = { bookTitle: page.bookTitle, author: page.author, source: location.hostname, indent: cfg.indent !== false }; try { if (page.isToc) { // ---- 目录模式 ---- let list = page.chapters; if (cfg.startIndex > 1 || cfg.endIndex > 0) { const s = Math.max(1, cfg.startIndex || 1); const e = cfg.endIndex > 0 ? Math.min(cfg.endIndex, list.length) : list.length; list = list.slice(s - 1, e); } if (cfg.maxChapters > 0) list = list.slice(0, cfg.maxChapters); panel = createPanel(page.bookTitle); panel.set('准备抓取 ' + list.length + ' 章…', 0); for (let i = 0; i < list.length; i++) { if (panel.state.cancelled) break; const item = list[i]; panel.set('(' + (i + 1) + '/' + list.length + ') ' + item.title, (i / list.length) * 100); const ch = await fetchChapter(item.url, cfg.selector); if (ch && ch.paragraphs && ch.paragraphs.length) { results.push({ title: item.title || ch.title, paragraphs: ch.paragraphs }); } else { failed++; log('失败:' + item.title + ' → ' + (ch && ch.error || '未知原因')); } await sleep(cfg.delay + Math.random() * 200); } } else { // ---- 连续模式:从当前章沿「下一章」往后抓 ---- panel = createPanel(page.bookTitle); let current = page.chapter; const seen = new Set([normalizeUrl(location.href)]); let guard = 0; while (current && guard < (cfg.maxChapters || 3000)) { guard++; if (panel.state.cancelled) break; results.push({ title: current.title, paragraphs: current.paragraphs }); panel.set('已抓取 ' + results.length + ' 章 · ' + current.title, 0); if (!current.nextUrl || seen.has(normalizeUrl(current.nextUrl))) break; seen.add(normalizeUrl(current.nextUrl)); const ch = await fetchChapter(current.nextUrl, cfg.selector); if (!ch || !ch.paragraphs || !ch.paragraphs.length) { if (ch && ch.error) log('连续抓取停止:' + ch.error); break; } current = ch; await sleep(cfg.delay + Math.random() * 200); } } if (!results.length) { const msg = '没有抓到任何正文,请确认页面或正文选择器。'; panel.fail(msg); return { ok: false, error: msg }; } const text = buildTxt(meta, results, failed); const filename = sanitizeName(page.bookTitle) + '.txt'; const size = downloadTxt(text, filename); panel.done('完成:' + results.length + ' 章' + (failed ? ',失败 ' + failed + ' 章' : '') + ';文件 ' + filename + '(' + (size / 1024 / 1024 >= 1 ? (size / 1024 / 1024).toFixed(1) + ' MB' : (size / 1024).toFixed(0) + ' KB') + ')'); log('已导出 ' + filename + ',共 ' + results.length + ' 章,' + results.reduce(function (s, r) { return s + r.paragraphs.join('').length; }, 0) + ' 字'); return { ok: true, file: filename, chapters: results.length, failed: failed }; } catch (e) { const msg = String(e && e.message || e); log('出错:' + msg); if (panel) panel.fail('出错:' + msg); return { ok: false, error: msg }; } finally { running = false; } } /* ========================= 对外接口 ========================= */ window.NovelDL = { version: VERSION, config: function (opts) { return Object.assign(CONFIG, opts || {}); }, analyze: function () { return analyzePage(document, location.href, CONFIG.selector); }, run: run, stop: function () { if (panel) panel.state.cancelled = true; } }; log('已加载 v' + VERSION + '。用法:NovelDL.run(),或 NovelDL.config({delay:1200}).run()'); if (CONFIG.autoRun) { // 只有当前页面确实像小说页(有目录或正文)才自动开始,避免在普通网页上打扰 setTimeout(function () { if (!CONFIG.autoRun) return; try { const page = analyzePage(document, location.href, CONFIG.selector); const looksLikeNovel = (page.isToc && page.chapters.length >= 3) || (page.chapter && page.chapter.charCount >= 60); if (looksLikeNovel) { run(); } else { log('当前页面没有识别到小说目录或正文,未自动开始。需要时手动执行 NovelDL.run()'); } } catch (e) {} }, 600); } })();