Skip to content

欢迎来到电子书下载宝库,一个汇聚了各类电子书下载链接的地方。无论你是喜欢阅读经典文学、经管励志、终身学习、职场创业、技术手册还是其他类型的书籍,这里都能满足你的需求。 该库涵盖了帆书app(原樊登读书)、微信读书、京东读书、喜马拉雅等读书app的大部分电子书。

Python

feat: 添加同步脚本和 GitHub Actions 工作流

jbiaojerrydb7739bb92e4
diff --git a/.github/workflows/full-sync.yml b/.github/workflows/full-sync.yml
new file mode 100644
index 0000000..5426091
--- /dev/null
+++ b/.github/workflows/full-sync.yml
@@ -0,0 +1,65 @@
+name: Full Sync Books
+
+permissions:
+ contents: write
+
+on:
+ workflow_dispatch: # 只允许手动触发
+ # 也可以添加一次性schedule,例如:
+ # schedule:
+ # - cron: '0 0 1 1 *' # 每年1月1日执行一次
+
+jobs:
+ full-sync:
+ runs-on: ubuntu-latest
+ timeout-minutes: 120 # 全量同步可能需要较长时间
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.10"
+
+ - name: Install dependencies
+ run: |
+ pip install requests beautifulsoup4 aiohttp
+
+ - name: Full sync books
+ env:
+ BOOK_SITE_DOMAIN: ${{ secrets.BOOK_SITE_DOMAIN }}
+ OUTPUT_DIR: md
+ run: |
+ # 检查环境变量
+ if [ -z "$BOOK_SITE_DOMAIN" ]; then
+ echo "❌ 错误: BOOK_SITE_DOMAIN 未设置"
+ echo "请在 GitHub Repository Settings > Secrets and variables > Actions 中添加 BOOK_SITE_DOMAIN"
+ exit 1
+ fi
+
+ echo "✅ BOOK_SITE_DOMAIN 已从GitHub Secrets加载"
+ echo "📁 输出目录: $OUTPUT_DIR"
+
+ # 运行全量同步脚本(会自动查找最大ID并更新README和all_books.json)
+ cd scripts/sync
+ python3 sync_all_books.py --skip-backup
+
+ - name: Commit and push changes
+ if: success() # 只有同步成功才提交
+ run: |
+ git config user.name "github-actions[bot]"
+ git config user.email "github-actions[bot]@users.noreply.github.com"
+
+ # 检查是否有变更
+ if [ -n "$(git status --porcelain)" ]; then
+ # 添加所有变更(md目录、README.md、all_books.json等)
+ git add md/ README.md docs/all-books.json docs/parse-stats.json || true
+ git commit -m "auto: full sync books and update README [skip ci]" || echo "No changes to commit"
+ git push
+ else
+ echo "No changes to commit"
+ fi
diff --git a/.github/workflows/generate-site.yml b/.github/workflows/generate-site.yml
index 3cd17de..fa2b2c6 100644
--- a/.github/workflows/generate-site.yml
+++ b/.github/workflows/generate-site.yml
@@ -10,6 +10,8 @@ on:
paths:
- "scripts/**"
- "md/**"
+ # 排除由同步脚本触发的提交(避免循环)
+ # 同步脚本使用 [skip ci] 标记,不会触发此工作流
jobs:
build:
@@ -27,8 +29,15 @@ jobs:
echo "No external dependencies required"
- name: Parse MD files to JSON
+ # 注意:all-books.json 通常已由同步脚本生成
+ # 这里确保all-books.json存在(如果不存在则生成)
run: |
- python scripts/parse_md_to_json.py
+ if [ ! -f "docs/all-books.json" ]; then
+ echo "⚠️ all-books.json 不存在,生成中..."
+ python scripts/parse_md_to_json.py
+ else
+ echo "✅ all-books.json 已存在(可能由同步脚本生成),跳过生成"
+ fi
- name: Generate index.html
run: |
diff --git a/.github/workflows/incremental-sync.yml b/.github/workflows/incremental-sync.yml
new file mode 100644
index 0000000..94926f7
--- /dev/null
+++ b/.github/workflows/incremental-sync.yml
@@ -0,0 +1,76 @@
+name: Incremental Sync Books
+
+permissions:
+ contents: write
+
+on:
+ schedule:
+ # 每天凌晨2点自动执行(UTC时间,即北京时间10点)
+ - cron: '0 2 * * *'
+ workflow_dispatch: # 允许手动触发
+
+jobs:
+ incremental-sync:
+ runs-on: ubuntu-latest
+ timeout-minutes: 60 # 增量同步通常较快
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.10"
+
+ - name: Install dependencies
+ run: |
+ pip install requests beautifulsoup4 aiohttp
+
+ - name: Incremental sync books
+ env:
+ BOOK_SITE_DOMAIN: ${{ secrets.BOOK_SITE_DOMAIN }}
+ OUTPUT_DIR: md
+ run: |
+ # 检查环境变量
+ if [ -z "$BOOK_SITE_DOMAIN" ]; then
+ echo "❌ 错误: BOOK_SITE_DOMAIN 未设置"
+ echo "请在 GitHub Repository Settings > Secrets and variables > Actions 中添加 BOOK_SITE_DOMAIN"
+ exit 1
+ fi
+
+ echo "✅ BOOK_SITE_DOMAIN 已从GitHub Secrets加载"
+ echo "📁 输出目录: $OUTPUT_DIR"
+
+ # 运行增量同步脚本
+ cd scripts/sync
+ python3 incremental_sync.py
+
+ - name: Update README and all_books.json
+ if: success() # 只有同步成功才更新
+ run: |
+ # 更新README.md的热门分类章节
+ echo "📝 更新README.md热门分类章节..."
+ python3 scripts/sync/update_readme_hot_categories.py || echo "⚠️ README更新失败,继续执行"
+
+ # 生成all_books.json
+ echo "📝 生成all_books.json..."
+ python3 scripts/parse_md_to_json.py || echo "⚠️ all_books.json生成失败,继续执行"
+
+ - name: Commit and push changes
+ if: success() # 只有同步成功才提交
+ run: |
+ git config user.name "github-actions[bot]"
+ git config user.email "github-actions[bot]@users.noreply.github.com"
+
+ # 检查是否有变更
+ if [ -n "$(git status --porcelain)" ]; then
+ # 添加所有变更(md目录、README.md、all_books.json等)
+ git add md/ README.md docs/all-books.json docs/parse-stats.json || true
+ git commit -m "auto: incremental sync books and update README [skip ci]" || echo "No changes to commit"
+ git push
+ else
+ echo "No changes to commit"
+ fi
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e7d1f4d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,29 @@
+# 配置文件(包含敏感信息)
+scripts/sync/config.py
+
+# 测试输出目录
+md_test/
+
+# 备份文件
+backup/
+md_backup/
+
+# Python缓存
+__pycache__/
+*.pyc
+*.pyo
+*.pyd
+
+# 环境变量文件
+.env
+.env.local
+
+# IDE配置
+.vscode/
+.idea/
+*.swp
+*.swo
+
+# 系统文件
+.DS_Store
+Thumbs.db
diff --git a/docs/search.js b/docs/search.js
index f3fc867..33c38af 100644
--- a/docs/search.js
+++ b/docs/search.js
@@ -71,10 +71,30 @@ function searchBooks(keyword) {
}).slice(0, MAX_RESULTS); // 限制结果数量
}
+// HTML 转义函数
+function escapeHtml(text) {
+ if (!text) return '';
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
+// 正则表达式特殊字符转义
+function escapeRegex(str) {
+ if (!str) return '';
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
function highlightText(text, keyword) {
- if (!keyword) return text;
- const regex = new RegExp(`(${keyword})`, 'gi');
- return text.replace(regex, '<mark>$1</mark>');
+ if (!keyword || !text) return escapeHtml(text);
+
+ // 转义正则表达式特殊字符,防止正则表达式注入
+ const escapedKeyword = escapeRegex(keyword);
+ const regex = new RegExp(`(${escapedKeyword})`, 'gi');
+
+ // 先转义 HTML,再添加高亮标记
+ const escapedText = escapeHtml(text);
+ return escapedText.replace(regex, '<mark>$1</mark>');
}
function renderResults(results, keyword) {
@@ -116,6 +136,22 @@ function renderResults(results, keyword) {
const highlightedAuthor = highlightText(b.author || "未知", keywordLower);
const highlightedCategory = highlightText(b.category || "", keywordLower);
+ // 验证和转义链接 URL,防止 javascript: 协议等 XSS 攻击
+ let safeLink = "#";
+ if (b.link) {
+ try {
+ const url = new URL(b.link, window.location.origin);
+ // 只允许 http、https 协议
+ if (url.protocol === 'http:' || url.protocol === 'https:') {
+ safeLink = url.href;
+ }
+ } catch (e) {
+ // 如果 URL 解析失败,使用原始链接(可能是相对路径)
+ // 但需要转义 HTML 特殊字符
+ safeLink = escapeHtml(b.link);
+ }
+ }
+
div.innerHTML = `
<div style="margin-bottom: 10px;">
<strong style="font-size: 16px; color: #93a1a1; font-weight: 600;">${highlightedTitle}</strong>
@@ -126,7 +162,7 @@ function renderResults(results, keyword) {
<span>📂 ${highlightedCategory}</span>
</div>
<div>
- <a href="${b.link}" target="_blank" rel="noopener" style="
+ <a href="${safeLink}" target="_blank" rel="noopener" style="
display: inline-block;
padding: 6px 14px;
background: #268bd2;
diff --git a/max_book_id_found.txt b/max_book_id_found.txt
new file mode 100644
index 0000000..af7b087
--- /dev/null
+++ b/max_book_id_found.txt
@@ -0,0 +1 @@
+64970
\ No newline at end of file
diff --git a/scripts/sync/backup_md.py b/scripts/sync/backup_md.py
new file mode 100644
index 0000000..3a1bb40
--- /dev/null
+++ b/scripts/sync/backup_md.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+备份现有的md目录
+"""
+
+import shutil
+from pathlib import Path
+from datetime import datetime
+import sys
+
+ROOT = Path(__file__).parent.parent.parent
+MD_DIR = ROOT / "md"
+BACKUP_DIR = ROOT / "md_backup"
+
+
+def backup_md_directory():
+ """备份md目录"""
+ print("=" * 80)
+ print("📦 备份md目录")
+ print("=" * 80)
+ print()
+
+ if not MD_DIR.exists():
+ print(f"⚠️ md目录不存在: {MD_DIR}")
+ print(" 无需备份")
+ return None
+
+ # 创建备份目录(带时间戳)
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ backup_path = BACKUP_DIR / f"md_backup_{timestamp}"
+
+ print(f"📁 源目录: {MD_DIR}")
+ print(f"📁 备份目录: {backup_path}")
+
+ try:
+ # 创建备份目录的父目录
+ backup_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # 复制目录
+ print("\n⏳ 正在备份...")
+ shutil.copytree(MD_DIR, backup_path)
+
+ # 统计文件数量
+ md_files = list(backup_path.glob("*.md"))
+ json_files = list(backup_path.glob("*.json"))
+
+ print(f"\n✅ 备份完成!")
+ print(f" - MD文件数: {len(md_files)}")
+ print(f" - JSON文件数: {len(json_files)}")
+ print(f" - 备份路径: {backup_path}")
+
+ return backup_path
+
+ except Exception as e:
+ print(f"\n❌ 备份失败: {e}")
+ return None
+
+
+if __name__ == "__main__":
+ backup_path = backup_md_directory()
+ if backup_path:
+ print(f"\n💾 备份已保存到: {backup_path}")
diff --git a/scripts/sync/find_max_book_id.py b/scripts/sync/find_max_book_id.py
new file mode 100644
index 0000000..62e8b80
--- /dev/null
+++ b/scripts/sync/find_max_book_id.py
@@ -0,0 +1,269 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+查找读书站中现有的最大书籍ID
+通过检查"最新书籍"页面来找到最大ID
+"""
+
+import requests
+import re
+from bs4 import BeautifulSoup
+from typing import Optional
+import os
+import sys
+
+# 尝试导入配置
+try:
+ from config import BOOK_SITE_DOMAIN
+except ImportError:
+ BOOK_SITE_DOMAIN = os.getenv("BOOK_SITE_DOMAIN", "")
+ if not BOOK_SITE_DOMAIN:
+ print("❌ 错误: 未配置 BOOK_SITE_DOMAIN")
+ print("请设置环境变量或创建 config.py")
+ sys.exit(1)
+
+
+def extract_book_id_from_url(url: str) -> Optional[int]:
+ """从URL中提取书籍ID"""
+ match = re.search(r'book-content-(\d+)\.html', url)
+ if match:
+ return int(match.group(1))
+ return None
+
+
+def find_max_book_id_from_homepage() -> Optional[int]:
+ """
+ 从首页的"最新书籍"列表中查找最大书籍ID
+
+ Returns:
+ 最大书籍ID,如果未找到返回None
+ """
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
+ 'Accept-Encoding': 'gzip, deflate, br',
+ 'Connection': 'keep-alive',
+ 'Upgrade-Insecure-Requests': '1',
+ }
+
+ try:
+ # 访问首页
+ url = f"{BOOK_SITE_DOMAIN}/"
+ print(f"📄 正在访问首页: {url}")
+
+ response = requests.get(url, headers=headers, timeout=10)
+ response.raise_for_status()
+
+ soup = BeautifulSoup(response.text, 'html.parser')
+
+ # 查找所有包含 book-content 的链接
+ book_links = soup.find_all('a', href=re.compile(r'book-content-\d+\.html'))
+
+ max_id = 0
+ found_ids = []
+
+ for link in book_links:
+ href = link.get('href', '')
+ book_id = extract_book_id_from_url(href)
+ if book_id:
+ found_ids.append(book_id)
+ if book_id > max_id:
+ max_id = book_id
+
+ if max_id > 0:
+ print(f"✅ 从首页找到 {len(found_ids)} 个书籍链接")
+ print(f"📊 最大书籍ID: {max_id}")
+ return max_id
+ else:
+ print("⚠️ 首页未找到书籍链接")
+ return None
+
+ except Exception as e:
+ print(f"❌ 访问首页失败: {e}")
+ return None
+
+
+def find_max_book_id_by_binary_search(start: int = 1, end: int = 100000) -> Optional[int]:
+ """
+ 使用二分查找法找到最大有效的书籍ID
+
+ Args:
+ start: 起始ID
+ end: 结束ID(预估的最大值)
+
+ Returns:
+ 最大有效的书籍ID
+ """
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
+ 'Accept-Encoding': 'gzip, deflate, br',
+ 'Connection': 'keep-alive',
+ 'Upgrade-Insecure-Requests': '1',
+ }
+
+ def check_book_exists(book_id: int) -> bool:
+ """检查书籍ID是否存在"""
+ url = f"{BOOK_SITE_DOMAIN}/book-content-{book_id}.html"
+ try:
+ response = requests.head(url, headers=headers, timeout=5, allow_redirects=False)
+ return response.status_code == 200
+ except:
+ return False
+
+ print(f"🔍 使用二分查找法查找最大书籍ID (范围: {start} - {end})")
+
+ left, right = start, end
+ max_valid_id = 0
+
+ # 先快速找到一个大致的上限
+ print("📊 步骤1: 快速定位大致范围...")
+ step = 1000
+ current = start
+ while current <= end:
+ if check_book_exists(current):
+ max_valid_id = current
+ current += step
+ else:
+ break
+ if current % 10000 == 0:
+ print(f" 已检查到 ID: {current}")
+
+ if max_valid_id == 0:
+ print("⚠️ 未找到任何有效书籍ID")
+ return None
+
+ print(f"✅ 找到大致范围,最大ID约在: {max_valid_id}")
+
+ # 在找到的范围内进行精确查找
+ print("📊 步骤2: 精确查找最大ID...")
+ left = max_valid_id
+ right = min(max_valid_id + step * 2, end)
+
+ while left <= right:
+ mid = (left + right) // 2
+ if check_book_exists(mid):
+ max_valid_id = mid
+ left = mid + 1
+ else:
+ right = mid - 1
+
+ if (left + right) // 2 % 100 == 0:
+ print(f" 当前范围: {left} - {right}, 最大有效ID: {max_valid_id}")
+
+ return max_valid_id
+
+
+def find_max_book_id_from_latest_books(max_pages: int = 10) -> Optional[int]:
+ """
+ 从"最新书籍"页面查找最大书籍ID(通过分页)
+
+ Args:
+ max_pages: 最多检查的页数
+
+ Returns:
+ 最大书籍ID
+ """
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
+ 'Accept-Encoding': 'gzip, deflate, br',
+ 'Connection': 'keep-alive',
+ 'Upgrade-Insecure-Requests': '1',
+ }
+
+ max_id = 0
+ page = 1
+
+ print(f"📄 正在检查最新书籍页面(最多 {max_pages} 页)...")
+
+ while page <= max_pages:
+ # 构建URL(首页是 /,后续可能是分页)
+ if page == 1:
+ url = f"{BOOK_SITE_DOMAIN}/"
+ else:
+ # 尝试不同的分页格式
+ url = f"{BOOK_SITE_DOMAIN}/book-{page}.html"
+
+ try:
+ response = requests.get(url, headers=headers, timeout=10)
+ if response.status_code != 200:
+ break
+
+ soup = BeautifulSoup(response.text, 'html.parser')
+ book_links = soup.find_all('a', href=re.compile(r'book-content-\d+\.html'))
+
+ if not book_links:
+ break
+
+ page_max_id = 0
+ for link in book_links:
+ href = link.get('href', '')
+ book_id = extract_book_id_from_url(href)
+ if book_id and book_id > page_max_id:
+ page_max_id = book_id
+
+ if page_max_id > max_id:
+ max_id = page_max_id
+ print(f" 第 {page} 页: 最大ID = {page_max_id}")
+
+ page += 1
+
+ except Exception as e:
+ print(f"⚠️ 检查第 {page} 页时出错: {e}")
+ break
+
+ if max_id > 0:
+ print(f"✅ 从最新书籍页面找到最大ID: {max_id}")
+ return max_id
+ else:
+ print("⚠️ 未从最新书籍页面找到有效ID")
+ return None
+
+
+def main():
+ """主函数:查找最大书籍ID"""
+ print("=" * 80)
+ print("🔍 查找读书站最大书籍ID")
+ print("=" * 80)
+ print()
+
+ # 方法1:从首页查找(最快)
+ print("方法1: 从首页查找...")
+ max_id = find_max_book_id_from_homepage()
+
+ if max_id:
+ print(f"\n✅ 找到最大书籍ID: {max_id}")
+ return max_id
+
+ # 方法2:从最新书籍页面查找
+ print("\n方法2: 从最新书籍页面查找...")
+ max_id = find_max_book_id_from_latest_books(max_pages=5)
+
+ if max_id:
+ print(f"\n✅ 找到最大书籍ID: {max_id}")
+ return max_id
+
+ # 方法3:使用二分查找(最可靠但较慢)
+ print("\n方法3: 使用二分查找法(较慢但更准确)...")
+ max_id = find_max_book_id_by_binary_search(start=1, end=100000)
+
+ if max_id:
+ print(f"\n✅ 找到最大书籍ID: {max_id}")
+ return max_id
+
+ print("\n❌ 未能找到最大书籍ID")
+ return None
+
+
+if __name__ == "__main__":
+ max_id = main()
+ if max_id:
+ print(f"\n📝 建议:使用 ID 范围 1-{max_id} 进行全量同步")
+ # 保存到文件
+ with open("max_book_id_found.txt", "w") as f:
+ f.write(str(max_id))
+ print(f"💾 最大ID已保存到: max_book_id_found.txt")
diff --git a/scripts/sync/incremental_sync.py b/scripts/sync/incremental_sync.py
new file mode 100644
index 0000000..fbb84bb
--- /dev/null
+++ b/scripts/sync/incremental_sync.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+增量同步脚本:比较已更新的最大书籍ID和读书站的最大ID,只处理新增书籍
+"""
+
+import sys
+import os
+from pathlib import Path
+import asyncio
+
+# 添加当前目录到路径
+sys.path.insert(0, str(Path(__file__).parent))
+
+# 设置环境变量,确保使用正式目录md/
+# 必须在导入test_batch_sync之前设置
+os.environ['OUTPUT_DIR'] = 'md'
+
+# 导入test_batch_sync(必须在设置环境变量后)
+from find_max_book_id import find_max_book_id_from_homepage
+from test_batch_sync import load_max_book_id, main as sync_main
+
+
+async def incremental_sync():
+ """执行增量同步"""
+ print("=" * 80)
+ print("🔄 增量同步书籍数据")
+ print("=" * 80)
+ print()
+
+ # 步骤1:获取已更新的最大书籍ID
+ print("📊 步骤1: 获取已更新的最大书籍ID")
+ print("-" * 80)
+ last_max_id = load_max_book_id()
+
+ if last_max_id == 0:
+ print("⚠️ 未找到已更新的最大ID,将执行全量同步")
+ print(" 建议先运行全量同步脚本")
+ return False
+
+ print(f"✅ 已更新的最大书籍ID: {last_max_id}")
+ print()
+
+ # 步骤2:查找读书站当前的最大ID
+ print("🔍 步骤2: 查找读书站当前的最大ID")
+ print("-" * 80)
+ current_max_id = find_max_book_id_from_homepage()
+
+ if not current_max_id:
+ print("❌ 未能找到读书站的最大ID")
+ return False
+
+ print(f"✅ 读书站当前最大ID: {current_max_id}")
+ print()
+
+ # 步骤3:比较并确定需要同步的范围
+ if current_max_id <= last_max_id:
+ print("✅ 没有新书籍需要同步")
+ print(f" 当前最大ID: {current_max_id}")
+ print(f" 已更新最大ID: {last_max_id}")
+ return True
+
+ new_books_count = current_max_id - last_max_id
+ print(f"📚 步骤3: 发现 {new_books_count} 本新书籍需要同步")
+ print(f" 同步范围: ID {last_max_id + 1} - {current_max_id}")
+ print()
+
+ # 步骤4:执行同步
+ print("⏳ 开始同步新书籍...")
+ sync_success = False
+ try:
+ await sync_main(last_max_id + 1, current_max_id)
+ sync_success = True
+ print("\n" + "=" * 80)
+ print("✅ 增量同步完成!")
+ print("=" * 80)
+ except Exception as e:
+ print(f"\n❌ 同步失败: {e}")
+ import traceback
+ traceback.print_exc()
+ return False
+
+ # 只有同步成功才更新README和all_books.json
+ if sync_success:
+ print("\n" + "=" * 80)
+ print("📝 步骤4: 更新README.md和all_books.json")
+ print("=" * 80)
+ print()
+
+ # 更新README.md的热门分类章节
+ print("📝 更新README.md热门分类章节...")
+ try:
+ from update_readme_hot_categories import update_readme
+ if update_readme():
+ print("✅ README.md已更新")
+ else:
+ print("⚠️ README.md更新失败,但继续执行")
+ except Exception as e:
+ print(f"⚠️ 更新README.md失败: {e}")
+
+ # 生成all_books.json
+ print("\n📝 生成all_books.json...")
+ try:
+ import subprocess
+ result = subprocess.run(
+ ["python3", str(Path(__file__).parent.parent.parent / "scripts" / "parse_md_to_json.py")],
+ cwd=str(Path(__file__).parent.parent.parent),
+ capture_output=True,
+ text=True
+ )
+ if result.returncode == 0:
+ print("✅ all_books.json已生成")
+ if result.stdout:
+ print(result.stdout)
+ else:
+ print(f"⚠️ 生成all_books.json失败: {result.stderr}")
+ except Exception as e:
+ print(f"⚠️ 生成all_books.json失败: {e}")
+
+ return sync_success
+
+
+if __name__ == "__main__":
+ success = asyncio.run(incremental_sync())
+ exit(0 if success else 1)
diff --git a/scripts/sync/parse_book_detail_enhanced.py b/scripts/sync/parse_book_detail_enhanced.py
new file mode 100644
index 0000000..719f83d
--- /dev/null
+++ b/scripts/sync/parse_book_detail_enhanced.py
@@ -0,0 +1,435 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+增强版书籍详情页解析模块
+功能:解析书籍详情页,提取完整信息(包括标签、图片等)
+"""
+
+import requests
+import re
+import os
+from bs4 import BeautifulSoup
+from urllib.parse import urljoin
+from typing import Dict, List, Optional
+
+# 尝试导入配置文件,如果不存在则使用环境变量或默认值
+try:
+ from config import BOOK_SITE_DOMAIN
+except ImportError:
+ # 如果配置文件不存在,尝试从环境变量读取
+ BOOK_SITE_DOMAIN = os.getenv("BOOK_SITE_DOMAIN", "")
+ if not BOOK_SITE_DOMAIN:
+ # 如果都没有,使用占位符(但会导致功能不可用)
+ BOOK_SITE_DOMAIN = ""
+
+
+def parse_download_page(url: str) -> Optional[Dict[str, str]]:
+ """
+ 解析下载页面,提取诚通网盘的真实下载链接
+
+ Args:
+ url: 下载页面 URL,例如: "https://www.dushupai.com/download-book-64938.html"
+
+ Returns:
+ Optional[Dict]: 如果找到诚通网盘下载链接,返回包含 download_url 的字典;
+ 如果不存在该下载方式,返回 None
+ """
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
+ 'Accept-Encoding': 'gzip, deflate, br',
+ 'Connection': 'keep-alive',
+ 'Upgrade-Insecure-Requests': '1',
+ }
+
+ try:
+ # 发送请求
+ response = requests.get(url, headers=headers, timeout=10)
+ response.raise_for_status()
+
+ # 解析 HTML
+ soup = BeautifulSoup(response.text, 'html.parser')
+
+ # 步骤1: 精确定位"诚通网盘下载"区域
+ # 方法1: 查找 class="source-title" 且包含"诚通网盘"的 div
+ cheng_tong_title = soup.find('div', class_='source-title', string=lambda x: x and '诚通网盘' in str(x) if x else False)
+
+ if not cheng_tong_title:
+ # 方法2: 查找包含"诚通网盘下载"文本的元素
+ cheng_tong_text = soup.find(string=lambda x: x and '诚通网盘下载' in str(x) if x else False)
+ if cheng_tong_text:
+ # 向上查找包含该文本的 source-title div
+ parent = cheng_tong_text.parent
+ while parent:
+ if parent.name == 'div' and 'source-title' in str(parent.get('class', [])):
+ cheng_tong_title = parent
+ break
+ if parent.name in ['body', 'html']:
+ break
+ parent = parent.parent
+
+ if not cheng_tong_title:
+ # 如果找不到"诚通网盘下载"区域,返回 None
+ return None
+
+ # 步骤2: 找到包含"诚通网盘下载"的容器(通常是 <div class="box">)
+ container = cheng_tong_title.parent
+ while container:
+ # 如果当前容器是 box,使用它
+ if container.name == 'div' and 'box' in str(container.get('class', [])):
+ break
+
+ # 检查当前容器是否包含 button
+ button_div = container.find('div', class_='button')
+ if button_div:
+ # 找到了包含按钮的容器
+ break
+
+ # 继续向上查找
+ container = container.parent
+
+ # 如果已经到 body 或 html,停止
+ if not container or container.name in ['body', 'html']:
+ container = None
+ break
+
+ if not container:
+ return None
+
+ # 步骤3: 在容器内查找"立即下载"按钮并提取链接
+ # 方法1: 查找 class="button" 的 div 中的链接(最精确)
+ button_div = container.find('div', class_='button')
+ if button_div:
+ download_link = button_div.find('a', href=True)
+ if download_link:
+ download_url = download_link.get('href', '').strip()
+ # 验证是否是 ctfile.com 链接
+ if download_url and 'ctfile.com' in download_url.lower():
+ return {
+ "download_url": download_url
+ }
+
+ # 方法2: 在容器内查找包含"立即下载"文本的链接
+ download_links = container.find_all('a', string=lambda x: x and '立即下载' in str(x) if x else False)
+ for link in download_links:
+ href = link.get('href', '').strip()
+ if href and 'ctfile.com' in href.lower():
+ return {
+ "download_url": href
+ }
+
+ # 方法3: 在容器内查找所有包含 ctfile.com 的链接(最后备用)
+ ctfile_links = container.find_all('a', href=lambda x: x and 'ctfile.com' in str(x).lower() if x else False)
+ if ctfile_links:
+ download_url = ctfile_links[0].get('href', '').strip()
+ if download_url:
+ return {
+ "download_url": download_url
+ }
+
+ # 如果都没找到,返回 None
+ return None
+
+ except requests.exceptions.RequestException as e:
+ return None
+ except Exception as e:
+ return None
+
+
+def extract_book_id(url: str) -> Optional[str]:
+ """
+ 从URL中提取书籍ID
+
+ Args:
+ url: 书籍详情页URL,例如: "https://www.dushupai.com/book-content-63067.html"
+
+ Returns:
+ 书籍ID字符串,例如: "63067"
+ """
+ match = re.search(r'book-content-(\d+)\.html', url)
+ if match:
+ return match.group(1)
+ return None
+
+
+def parse_book_detail_enhanced(url: str) -> Dict:
+ """
+ 解析书籍详情页,提取完整信息
+
+ Args:
+ url: 书籍详情页 URL,例如: "https://www.dushupai.com/book-content-63067.html"
+
+ Returns:
+ Dict: 包含以下字段的字典:
+ - book_id: 书籍ID
+ - title: 书名
+ - author: 作者信息
+ - cover_image: 封面图片URL
+ - download_page: 下载页面URL
+ - download_url: 实际下载链接(需要进一步解析下载页)
+ - tags: 标签列表
+ - category: 分类
+ - isbn: ISBN号
+ - rating: 评分
+ - publish_date: 发布日期
+ - description: 内容简介
+ - author_bio: 作者简介
+ """
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
+ 'Accept-Encoding': 'gzip, deflate, br',
+ 'Connection': 'keep-alive',
+ 'Upgrade-Insecure-Requests': '1',
+ }
+
+ result = {
+ "book_id": extract_book_id(url) or "",
+ "title": "",
+ "author": "未知",
+ "cover_image": "",
+ "download_page": "",
+ "download_url": "",
+ "tags": [],
+ "category": "",
+ "isbn": "",
+ "rating": "",
+ "publish_date": "",
+ "description": "",
+ "author_bio": "",
+ "formats": []
+ }
+
+ try:
+ # 发送请求
+ response = requests.get(url, headers=headers, timeout=10)
+ response.raise_for_status()
+
+ # 解析 HTML
+ soup = BeautifulSoup(response.text, 'html.parser')
+
+ # 1. 提取书名
+ title_elem = soup.select_one('h4.post-title')
+ if title_elem:
+ result["title"] = title_elem.get_text(strip=True)
+
+ if not result["title"]:
+ post_info = soup.select_one('.post-info')
+ if post_info:
+ for li in post_info.find_all('li'):
+ strong = li.find('strong')
+ if strong and '书名' in strong.get_text():
+ title_text = li.get_text().replace('书名:', '').strip()
+ if title_text:
+ result["title"] = title_text
+ break
+
+ # 2. 提取作者信息
+ post_info = soup.select_one('.post-info')
+ if post_info:
+ for li in post_info.find_all('li'):
+ strong = li.find('strong')
+ if strong and '作者' in strong.get_text():
+ author_links = li.find_all('a', href=lambda x: x and 'book-author' in str(x) if x else False)
+ if author_links:
+ authors = [link.get_text(strip=True) for link in author_links if link.get_text(strip=True)]
+ if authors:
+ result["author"] = " / ".join(authors)
+ else:
+ author_text = li.get_text().replace('作者:', '').strip()
+ if author_text:
+ result["author"] = author_text
+ break
+
+ # 3. 提取封面图片
+ img_elem = soup.select_one('.post-content img')
+ if img_elem:
+ img_src = img_elem.get('src', '')
+ if img_src:
+ result["cover_image"] = urljoin(url, img_src)
+
+ # 4. 提取下载页面URL并解析实际下载链接
+ download_elem = soup.select_one('.post-download a')
+ if download_elem:
+ download_href = download_elem.get('href', '')
+ if download_href:
+ result["download_page"] = urljoin(url, download_href)
+
+ # 解析下载页面,获取诚通网盘的实际下载链接
+ try:
+ download_info = parse_download_page(result["download_page"])
+ if download_info and download_info.get("download_url"):
+ result["download_url"] = download_info["download_url"]
+ except Exception as e:
+ # 如果解析失败,不影响其他信息的提取
+ pass
+
+ # 5. 提取标签列表(关键功能)
+ # 方法1:直接查找包含 book-tag 的链接(最可靠)
+ tag_links = soup.find_all('a', href=lambda x: x and 'book-tag' in str(x) if x else False)
+ if tag_links:
+ tags = []
+ for link in tag_links:
+ tag_text = link.get_text(strip=True)
+ # 格式可能是 "中国(5333)" 或 "中国"
+ if '(' in tag_text:
+ tag_name = tag_text.split('(')[0].strip()
+ else:
+ tag_name = tag_text
+
+ # 过滤掉空标签和数字标签(如年份)
+ if tag_name and tag_name not in tags:
+ # 跳过纯数字标签(如年份)
+ if not tag_name.isdigit():
+ tags.append(tag_name)
+
+ result["tags"] = tags
+
+ # 方法2:如果方法1没找到,尝试查找"标签:"后面的内容
+ if not result["tags"]:
+ for elem in soup.find_all(['div', 'p', 'span', 'strong']):
+ text = elem.get_text()
+ if '标签' in text and (':' in text or ':' in text):
+ # 查找父元素或兄弟元素中的标签链接
+ parent = elem.find_parent()
+ if parent:
+ tag_links = parent.find_all('a', href=lambda x: x and 'book-tag' in str(x) if x else False)
+ if tag_links:
+ tags = []
+ for link in tag_links:
+ tag_text = link.get_text(strip=True)
+ if '(' in tag_text:
+ tag_name = tag_text.split('(')[0].strip()
+ else:
+ tag_name = tag_text
+ if tag_name and tag_name not in tags and not tag_name.isdigit():
+ tags.append(tag_name)
+ if tags:
+ result["tags"] = tags
+ break
+
+ # 6. 提取分类
+ category_link = soup.find('a', href=lambda x: x and 'book-category' in str(x) if x else False)
+ if category_link:
+ result["category"] = category_link.get_text(strip=True)
+
+ # 7. 提取其他信息(ISBN、评分、发布日期等)
+ if post_info:
+ for li in post_info.find_all('li'):
+ strong = li.find('strong')
+ if not strong:
+ continue
+
+ strong_text = strong.get_text()
+ li_text = li.get_text()
+
+ if 'ISBN' in strong_text:
+ result["isbn"] = li_text.replace('ISBN:', '').replace('ISBN:', '').strip()
+ elif '评分' in strong_text:
+ rating_text = li_text.replace('评分:', '').replace('评分:', '').strip()
+ result["rating"] = rating_text
+ elif '时间' in strong_text or '日期' in strong_text:
+ date_text = li_text.replace('时间:', '').replace('日期:', '').strip()
+ result["publish_date"] = date_text
+ elif '格式' in strong_text:
+ formats_text = li_text.replace('格式:', '').replace('格式:', '').strip()
+ result["formats"] = [f.strip() for f in formats_text.split(',') if f.strip()]
+
+ # 8. 提取内容简介
+ desc_elem = soup.find(string=re.compile(r'内容简介'))
+ if desc_elem:
+ # 查找简介内容(通常在"内容简介"后面的元素中)
+ parent = desc_elem.find_parent()
+ if parent:
+ # 查找下一个兄弟元素或父元素中的文本
+ desc_text = ""
+ for sibling in parent.next_siblings:
+ if hasattr(sibling, 'get_text'):
+ desc_text = sibling.get_text(strip=True)
+ if desc_text:
+ break
+
+ if not desc_text:
+ # 尝试从父元素中提取
+ desc_text = parent.get_text(strip=True)
+ # 去掉"内容简介:"前缀
+ desc_text = re.sub(r'内容简介[::]?\s*', '', desc_text)
+
+ result["description"] = desc_text[:500] # 限制长度
+
+ # 9. 提取作者简介
+ author_bio_elem = soup.find(string=re.compile(r'作者简介'))
+ if author_bio_elem:
+ parent = author_bio_elem.find_parent()
+ if parent:
+ bio_text = ""
+ for sibling in parent.next_siblings:
+ if hasattr(sibling, 'get_text'):
+ bio_text = sibling.get_text(strip=True)
+ if bio_text:
+ break
+
+ if not bio_text:
+ bio_text = parent.get_text(strip=True)
+ bio_text = re.sub(r'作者简介[::]?\s*', '', bio_text)
+
+ result["author_bio"] = bio_text[:300] # 限制长度
+
+ return result
+
+ except requests.exceptions.RequestException as e:
+ print(f"❌ 请求失败: {e}")
+ return result
+ except Exception as e:
+ print(f"❌ 解析过程出错: {e}")
+ import traceback
+ traceback.print_exc()
+ return result
+
+
+def main():
+ """主函数:测试增强版解析功能"""
+ print("=" * 80)
+ print("📚 测试增强版 parse_book_detail_enhanced 功能")
+ print("=" * 80)
+
+ # 测试 URL
+ test_url = "https://www.dushupai.com/book-content-63067.html"
+
+ print(f"\n📄 测试 URL: {test_url}\n")
+
+ # 解析书籍详情
+ result = parse_book_detail_enhanced(test_url)
+
+ # 显示结果
+ print("📋 解析结果:")
+ print("-" * 80)
+ print(f"书籍ID: {result['book_id']}")
+ print(f"书名: {result['title']}")
+ print(f"作者: {result['author']}")
+ print(f"封面图片: {result['cover_image']}")
+ print(f"下载页面: {result['download_page']}")
+ print(f"标签: {', '.join(result['tags']) if result['tags'] else '无'}")
+ print(f"分类: {result['category']}")
+ print(f"ISBN: {result['isbn']}")
+ print(f"评分: {result['rating']}")
+ print(f"发布日期: {result['publish_date']}")
+ print(f"格式: {', '.join(result['formats']) if result['formats'] else '无'}")
+ print(f"简介: {result['description'][:100]}..." if result['description'] else "无简介")
+
+ # 显示 JSON 格式
+ print("\n📋 JSON 格式:")
+ import json
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+
+ print("\n" + "=" * 80)
+ print("✅ 测试完成!")
+ print("=" * 80)
+
+ return result
+
+
+if __name__ == "__main__":
+ result = main()
diff --git a/scripts/sync/run_full_sync.sh b/scripts/sync/run_full_sync.sh
new file mode 100755
index 0000000..1fb88c0
--- /dev/null
+++ b/scripts/sync/run_full_sync.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+# 全量同步一键执行脚本
+
+cd "$(dirname "$0")"
+
+echo "=========================================="
+echo "🚀 全量同步书籍数据"
+echo "=========================================="
+echo ""
+
+# 检查配置文件
+if [ ! -f "config.py" ]; then
+ echo "⚠️ 配置文件不存在,正在创建..."
+ cp config.py.example config.py
+ echo "✅ 已创建 config.py,请编辑并设置 BOOK_SITE_DOMAIN"
+ echo ""
+ read -p "按回车键继续(确保已配置config.py)..."
+fi
+
+# 执行全量同步
+echo "开始执行全量同步..."
+python3 sync_all_books.py
+
+echo ""
+echo "=========================================="
+echo "✅ 执行完成"
+echo "=========================================="
diff --git a/scripts/sync/sync_all_books.py b/scripts/sync/sync_all_books.py
new file mode 100644
index 0000000..88fc8bf
--- /dev/null
+++ b/scripts/sync/sync_all_books.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+全量同步脚本:备份现有md目录,查找最大书籍ID,然后生成所有书籍的md文件
+"""
+
+import sys
+import argparse
+import os
+from pathlib import Path
+import subprocess
+
+# 添加当前目录到路径
+sys.path.insert(0, str(Path(__file__).parent))
+
+# 注意:不在这里导入test_batch_sync,因为需要先设置环境变量
+from backup_md import backup_md_directory
+from find_max_book_id import find_max_book_id_from_homepage, find_max_book_id_by_binary_search
+
+
+def main():
+ """主函数"""
+ parser = argparse.ArgumentParser(description='全量同步书籍数据')
+ parser.add_argument('--max-id', type=int, help='手动指定最大书籍ID(跳过查找步骤)')
+ parser.add_argument('--skip-backup', action='store_true', help='跳过备份步骤')
+ parser.add_argument('--skip-find-id', action='store_true', help='跳过查找最大ID步骤(需要提供--max-id)')
+ parser.add_argument('--start-id', type=int, default=1, help='起始书籍ID(默认:1)')
+
+ args = parser.parse_args()
+
+ print("=" * 80)
+ print("🚀 全量同步书籍数据")
+ print("=" * 80)
+ print()
+
+ # 步骤1:备份现有md目录
+ if not args.skip_backup:
+ print("📦 步骤1: 备份现有md目录")
+ print("-" * 80)
+ backup_path = backup_md_directory()
+ if backup_path:
+ print(f"✅ 备份完成: {backup_path}\n")
+ else:
+ print("⚠️ 备份失败或目录不存在,继续执行...\n")
+ else:
+ print("⏭️ 跳过备份步骤\n")
+
+ # 步骤2:查找最大书籍ID
+ max_book_id = None
+ if not args.skip_find_id:
+ if args.max_id:
+ max_book_id = args.max_id
+ print(f"📊 使用指定的最大书籍ID: {max_book_id}\n")
+ else:
+ print("🔍 步骤2: 查找最大书籍ID")
+ print("-" * 80)
+ # 先尝试从首页快速查找
+ max_book_id = find_max_book_id_from_homepage()
+
+ # 如果首页没找到,使用二分查找(较慢但准确)
+ if not max_book_id:
+ print("\n使用二分查找法(较慢但更准确)...")
+ max_book_id = find_max_book_id_by_binary_search(start=1, end=100000)
+
+ if max_book_id:
+ print(f"\n✅ 找到最大书籍ID: {max_book_id}\n")
+ else:
+ print("\n❌ 未能找到最大书籍ID")
+ print(" 请手动指定: python3 sync_all_books.py --max-id <ID>")
+ return
+ else:
+ if args.max_id:
+ max_book_id = args.max_id
+ else:
+ print("❌ 错误: 跳过查找ID步骤时必须提供 --max-id")
+ return
+
+ # 步骤3:生成所有书籍的md文件
+ print("📚 步骤3: 生成所有书籍的md文件")
+ print("-" * 80)
+ print(f"📊 处理范围: ID {args.start_id} - {max_book_id}")
+ print(f"📊 预计书籍数量: {max_book_id - args.start_id + 1}")
+ print()
+
+ # 设置环境变量,确保使用正式目录md/
+ # 必须在导入test_batch_sync之前设置
+ os.environ['OUTPUT_DIR'] = 'md'
+
+ # 现在导入test_batch_sync(会读取环境变量)
+ import test_batch_sync
+ import asyncio
+
+ print("⏳ 开始处理,这可能需要较长时间...")
+ print("💡 提示:可以随时中断(Ctrl+C),下次运行会自动跳过已处理的ID")
+ print(f"💡 预计时间:约 {((max_book_id - args.start_id + 1) * 0.5 / 60):.1f} 分钟(基于0.5秒/请求)\n")
+
+ sync_success = False
+ try:
+ # 调用test_batch_sync的main函数,传入ID范围
+ asyncio.run(test_batch_sync.main(args.start_id, max_book_id))
+ sync_success = True
+ print("\n" + "=" * 80)
+ print("✅ 全量同步完成!")
+ print("=" * 80)
+ except KeyboardInterrupt:
+ print("\n\n⚠️ 用户中断,已保存进度")
+ print(" 下次运行时会自动从上次中断的地方继续")
+ return
+ except Exception as e:
+ print(f"\n❌ 执行出错: {e}")
+ import traceback
+ traceback.print_exc()
+ return
+
+ # 只有同步成功才更新README和all_books.json
+ if sync_success:
+ print("\n" + "=" * 80)
+ print("📝 步骤4: 更新README.md和all_books.json")
+ print("=" * 80)
+ print()
+
+ # 更新README.md的热门分类章节
+ print("📝 更新README.md热门分类章节...")
+ try:
+ from update_readme_hot_categories import update_readme
+ if update_readme():
+ print("✅ README.md已更新")
+ else:
+ print("⚠️ README.md更新失败,但继续执行")
+ except Exception as e:
+ print(f"⚠️ 更新README.md失败: {e}")
+
+ # 生成all_books.json
+ print("\n📝 生成all_books.json...")
+ try:
+ import subprocess
+ result = subprocess.run(
+ ["python3", str(Path(__file__).parent.parent.parent / "scripts" / "parse_md_to_json.py")],
+ cwd=str(Path(__file__).parent.parent.parent),
+ capture_output=True,
+ text=True
+ )
+ if result.returncode == 0:
+ print("✅ all_books.json已生成")
+ if result.stdout:
+ print(result.stdout)
+ else:
+ print(f"⚠️ 生成all_books.json失败: {result.stderr}")
+ except Exception as e:
+ print(f"⚠️ 生成all_books.json失败: {e}")
+
+ print("\n" + "=" * 80)
+ print("✅ 全量同步及后续更新完成!")
+ print("=" * 80)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/sync/test_batch_sync.py b/scripts/sync/test_batch_sync.py
new file mode 100644
index 0000000..af6bee3
--- /dev/null
+++ b/scripts/sync/test_batch_sync.py
@@ -0,0 +1,416 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+批量测试脚本:根据书籍ID批量处理并生成md文件
+测试范围:ID 1-1000
+"""
+
+import asyncio
+import aiohttp
+import time
+from pathlib import Path
+from collections import defaultdict
+from typing import Dict, List, Set
+import json
+import sys
+
+# 添加当前目录到路径
+sys.path.insert(0, str(Path(__file__).parent))
+
+from parse_book_detail_enhanced import parse_book_detail_enhanced
+
+# 尝试导入配置文件,如果不存在则使用环境变量
+import os
+try:
+ from config import BOOK_SITE_DOMAIN
+except ImportError:
+ # 如果配置文件不存在,尝试从环境变量读取(GitHub Actions会使用这种方式)
+ BOOK_SITE_DOMAIN = os.getenv("BOOK_SITE_DOMAIN", "")
+ if not BOOK_SITE_DOMAIN:
+ print("⚠️ 警告:未找到配置文件 config.py,也未设置环境变量 BOOK_SITE_DOMAIN")
+ print(" 本地运行:请复制 config.py.example 为 config.py 并配置 BOOK_SITE_DOMAIN")
+ print(" GitHub Actions:请在 Repository Settings > Secrets 中添加 BOOK_SITE_DOMAIN")
+ print(" 或设置环境变量: export BOOK_SITE_DOMAIN='https://www.dushupai.com'")
+ sys.exit(1)
+
+# 配置
+BASE_URL = f"{BOOK_SITE_DOMAIN}/book-content-{{}}.html"
+# 输出目录:根据环境变量决定是测试目录还是正式目录
+OUTPUT_DIR_ENV = os.getenv("OUTPUT_DIR", "md_test")
+if OUTPUT_DIR_ENV == "md":
+ OUTPUT_DIR = Path(__file__).parent.parent.parent / "md" # 正式目录
+else:
+ OUTPUT_DIR = Path(__file__).parent.parent.parent / "md_test" # 测试目录
+PROCESSED_IDS_FILE = OUTPUT_DIR / "processed_ids.json"
+STATS_FILE = OUTPUT_DIR / "stats.json"
+MAX_BOOK_ID_FILE = OUTPUT_DIR / "max_book_id.json" # 记录最大书籍ID
+
+# 并发配置
+MAX_CONCURRENT = 20 # 最大并发数
+REQUEST_DELAY = 0.5 # 请求延迟(秒)
+
+
+def sanitize_filename(filename: str) -> str:
+ """
+ 清理文件名,移除不合法字符
+
+ Args:
+ filename: 原始文件名
+
+ Returns:
+ 清理后的文件名
+ """
+ # 替换不合法字符
+ invalid_chars = ['/', '\\', ':', '*', '?', '"', '<', '>', '|']
+ for char in invalid_chars:
+ filename = filename.replace(char, '_')
+
+ # 移除首尾空格和点
+ filename = filename.strip(' .')
+
+ # 限制长度
+ if len(filename) > 200:
+ filename = filename[:200]
+
+ return filename or "未命名"
+
+
+def generate_md_file(tag_name: str, books: List[Dict], output_dir: Path) -> Path:
+ """
+ 生成Markdown文件
+
+ Args:
+ tag_name: 标签名称
+ books: 书籍列表
+ output_dir: 输出目录
+
+ Returns:
+ 生成的文件路径
+ """
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ # 清理文件名
+ safe_filename = sanitize_filename(tag_name)
+ file_path = output_dir / f"{safe_filename}.md"
+
+ # 过滤有效书籍(必须有书名和下载链接)
+ valid_books = []
+ for book in books:
+ title = book.get('title', '').strip()
+ # 优先使用实际下载链接(诚通网盘链接),避免使用下载页面链接(包含敏感域名)
+ download_url = book.get('download_url', '').strip()
+
+ # 如果没有实际下载链接,跳过该书(不包含下载页面链接以保护隐私)
+ if not download_url:
+ continue
+
+ if title and download_url:
+ valid_books.append({
+ 'title': title,
+ 'author': book.get('author', '未知').strip() or '未知',
+ 'download_url': download_url
+ })
+
+ if not valid_books:
+ return None
+
+ # 生成Markdown内容
+ lines = []
+ lines.append("| 书名 | 作者 | epub/mobi/azw3 |")
+ lines.append("| --- | --- | --- |")
+
+ for book in valid_books:
+ # 转义Markdown特殊字符
+ title_escaped = book['title'].replace('|', '\\|')
+ author_escaped = book['author'].replace('|', '\\|')
+ # 修改下载链接:将 ?pwd= 改成 ?p=
+ download_url = book['download_url'].replace('?pwd=', '?p=')
+
+ # 隐私保护:如果下载链接包含敏感域名,移除该书籍(不生成到md文件)
+ # 这样可以确保GitHub仓库中不包含敏感域名
+ if download_url and BOOK_SITE_DOMAIN in download_url:
+ # 跳过包含敏感域名的链接(通常是下载页面链接)
+ # 只保留诚通网盘的实际下载链接
+ continue
+
+ download_link = f"[下载]({download_url})"
+
+ lines.append(f"| {title_escaped} | {author_escaped} | {download_link} |")
+
+ # 写入文件
+ file_path.write_text('\n'.join(lines), encoding='utf-8')
+ return file_path
+
+
+async def fetch_book_async(session: aiohttp.ClientSession, book_id: int, semaphore: asyncio.Semaphore) -> Dict:
+ """
+ 异步获取书籍信息
+
+ Args:
+ session: aiohttp会话
+ book_id: 书籍ID
+ semaphore: 信号量控制并发
+
+ Returns:
+ 书籍信息字典,失败返回None
+ """
+ async with semaphore:
+ url = BASE_URL.format(book_id)
+
+ try:
+ # 添加延迟避免请求过快
+ await asyncio.sleep(REQUEST_DELAY)
+
+ # 使用同步请求(因为parse_book_detail_enhanced是同步的)
+ # 在实际生产环境中,可以改为异步版本
+ loop = asyncio.get_event_loop()
+ result = await loop.run_in_executor(None, parse_book_detail_enhanced, url)
+
+ # 检查是否成功获取到书名(判断书籍是否存在)
+ if result.get('title'):
+ result['book_id'] = str(book_id)
+ return result
+ else:
+ return None
+
+ except Exception as e:
+ print(f"❌ 处理书籍ID {book_id} 时出错: {e}")
+ return None
+
+
+async def batch_process_books(book_ids: List[int]) -> Dict[str, List[Dict]]:
+ """
+ 批量处理书籍
+
+ Args:
+ book_ids: 书籍ID列表
+
+ Returns:
+ 按标签分类的书籍字典 {tag: [books]}
+ """
+ # 按标签分类的书籍
+ books_by_tag = defaultdict(list)
+
+ # 创建信号量控制并发
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT)
+
+ # 创建aiohttp会话
+ async with aiohttp.ClientSession() as session:
+ # 创建任务列表
+ tasks = [fetch_book_async(session, book_id, semaphore) for book_id in book_ids]
+
+ # 处理结果
+ completed = 0
+ total = len(tasks)
+
+ for coro in asyncio.as_completed(tasks):
+ book_data = await coro
+ completed += 1
+
+ if book_data:
+ # 按标签分类
+ tags = book_data.get('tags', [])
+ if tags:
+ for tag in tags:
+ books_by_tag[tag].append(book_data)
+ else:
+ # 如果没有标签,使用分类作为标签
+ category = book_data.get('category', '未分类')
+ if category:
+ books_by_tag[category].append(book_data)
+ else:
+ books_by_tag['未分类'].append(book_data)
+
+ # 显示进度
+ if completed % 10 == 0 or completed == total:
+ print(f"📊 进度: {completed}/{total} ({completed*100//total}%) - 已找到 {len(books_by_tag)} 个标签")
+ else:
+ if completed % 50 == 0 or completed == total:
+ print(f"📊 进度: {completed}/{total} ({completed*100//total}%)")
+
+ return dict(books_by_tag)
+
+
+def save_processed_ids(book_ids: Set[int]):
+ """保存已处理的ID列表"""
+ PROCESSED_IDS_FILE.parent.mkdir(parents=True, exist_ok=True)
+ with open(PROCESSED_IDS_FILE, 'w', encoding='utf-8') as f:
+ json.dump(sorted(book_ids), f, ensure_ascii=False, indent=2)
+
+
+def load_processed_ids() -> Set[int]:
+ """加载已处理的ID列表"""
+ if PROCESSED_IDS_FILE.exists():
+ with open(PROCESSED_IDS_FILE, 'r', encoding='utf-8') as f:
+ return set(json.load(f))
+ return set()
+
+
+def save_stats(stats: Dict):
+ """保存统计信息"""
+ with open(STATS_FILE, 'w', encoding='utf-8') as f:
+ json.dump(stats, f, ensure_ascii=False, indent=2)
+
+
+def save_max_book_id(max_id: int):
+ """保存最大书籍ID"""
+ with open(MAX_BOOK_ID_FILE, 'w', encoding='utf-8') as f:
+ json.dump({'max_book_id': max_id, 'last_updated': time.strftime('%Y-%m-%d %H:%M:%S')},
+ f, ensure_ascii=False, indent=2)
+
+
+def load_max_book_id() -> int:
+ """加载最大书籍ID"""
+ if MAX_BOOK_ID_FILE.exists():
+ with open(MAX_BOOK_ID_FILE, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ return data.get('max_book_id', 0)
+ return 0
+
+
+def generate_hot_categories_index(books_by_tag: Dict[str, List[Dict]], output_dir: Path) -> Path:
+ """
+ 生成热门分类索引文件(按照README.md格式)
+
+ Args:
+ books_by_tag: 按标签分类的书籍字典
+ output_dir: 输出目录
+
+ Returns:
+ 生成的文件路径
+ """
+ output_dir.mkdir(parents=True, exist_ok=True)
+ file_path = output_dir / "热门分类.md"
+
+ # 按书籍数量排序
+ sorted_tags = sorted(books_by_tag.items(), key=lambda x: len(x[1]), reverse=True)
+
+ # 生成内容
+ lines = []
+ lines.append("# 📚 热门分类")
+ lines.append("")
+ lines.append("> **💡 使用 Ctrl+F 快速搜索关键词,或点击下方标签直接进入分类页面**")
+ lines.append("")
+ lines.append("## 🔥 热门分类")
+ lines.append("")
+
+ # 每行8个标签
+ items_per_line = 8
+ for i in range(0, len(sorted_tags), items_per_line):
+ batch = sorted_tags[i:i + items_per_line]
+ line_items = []
+
+ for tag, books in batch:
+ count = len(books)
+ # 清理文件名(与generate_md_file中的逻辑一致)
+ safe_filename = sanitize_filename(tag)
+ link = f"- [{tag}({count})]({safe_filename}.md)"
+ line_items.append(link)
+
+ # 用 | 分隔,每行8个
+ line = " | ".join(line_items)
+ lines.append(line)
+
+ # 写入文件
+ file_path.write_text('\n'.join(lines), encoding='utf-8')
+ return file_path
+
+
+async def main(start_id: int = 1, end_id: int = 1000):
+ """
+ 主函数
+
+ Args:
+ start_id: 起始书籍ID(默认:1)
+ end_id: 结束书籍ID(默认:1000)
+ """
+ print("=" * 80)
+ print(f"🚀 开始批量处理书籍(ID: {start_id}-{end_id})")
+ print("=" * 80)
+
+ # 创建输出目录
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+ print(f"📁 输出目录: {OUTPUT_DIR}")
+
+ # 生成书籍ID列表
+ book_ids = list(range(start_id, end_id + 1))
+ print(f"📚 待处理书籍数量: {len(book_ids)}")
+
+ # 加载已处理的ID(用于断点续传)
+ processed_ids = load_processed_ids()
+ if processed_ids:
+ print(f"📋 已处理ID数量: {len(processed_ids)}")
+ book_ids = [bid for bid in book_ids if bid not in processed_ids]
+ print(f"📚 剩余待处理: {len(book_ids)}")
+
+ if not book_ids:
+ print("✅ 所有书籍已处理完成!")
+ return
+
+ # 开始处理
+ start_time = time.time()
+ books_by_tag = await batch_process_books(book_ids)
+ elapsed_time = time.time() - start_time
+
+ # 统计信息
+ total_books = sum(len(books) for books in books_by_tag.values())
+ total_tags = len(books_by_tag)
+
+ print(f"\n📊 处理完成!")
+ print(f" - 总耗时: {elapsed_time:.2f} 秒")
+ print(f" - 成功处理: {total_books} 本书")
+ print(f" - 标签数量: {total_tags} 个")
+
+ # 生成md文件
+ print(f"\n📝 开始生成Markdown文件...")
+ generated_files = []
+
+ for tag, books in sorted(books_by_tag.items()):
+ file_path = generate_md_file(tag, books, OUTPUT_DIR)
+ if file_path:
+ generated_files.append(str(file_path))
+ # 如果文件数量很多,减少输出频率
+ if len(generated_files) <= 50 or len(generated_files) % 50 == 0:
+ print(f" ✅ {tag}: {len(books)} 本书 -> {file_path.name}")
+
+ print(f"\n✅ 共生成 {len(generated_files)} 个Markdown文件")
+
+ # 保存统计信息
+ stats = {
+ 'total_processed': total_books,
+ 'total_tags': total_tags,
+ 'generated_files': len(generated_files),
+ 'elapsed_time': elapsed_time,
+ 'tags': {tag: len(books) for tag, books in sorted(books_by_tag.items())}
+ }
+ save_stats(stats)
+
+ # 保存已处理的ID
+ all_processed = processed_ids | set(book_ids)
+ save_processed_ids(all_processed)
+
+ # 保存最大书籍ID(用于增量更新)
+ if book_ids:
+ max_id = max(book_ids)
+ save_max_book_id(max_id)
+ print(f"\n📊 最大书籍ID: {max_id}(已保存,用于增量更新)")
+
+ # 生成热门分类索引文件
+ print(f"\n📝 生成热门分类索引文件...")
+ hot_categories_file = generate_hot_categories_index(books_by_tag, OUTPUT_DIR)
+ print(f" ✅ 热门分类索引: {hot_categories_file.name}")
+
+ print(f"\n📈 统计信息已保存: {STATS_FILE}")
+ print("=" * 80)
+ print("✅ 测试完成!")
+ print("=" * 80)
+
+
+if __name__ == "__main__":
+ import argparse
+ parser = argparse.ArgumentParser(description='批量处理书籍并生成md文件')
+ parser.add_argument('--start-id', type=int, default=1, help='起始书籍ID(默认:1)')
+ parser.add_argument('--end-id', type=int, default=1000, help='结束书籍ID(默认:1000)')
+ args = parser.parse_args()
+
+ asyncio.run(main(args.start_id, args.end_id))
diff --git a/scripts/sync/update_readme_hot_categories.py b/scripts/sync/update_readme_hot_categories.py
new file mode 100644
index 0000000..b019699
--- /dev/null
+++ b/scripts/sync/update_readme_hot_categories.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+更新README.md中的"热门分类"章节
+根据md目录下的所有md文件生成热门分类列表
+"""
+
+import re
+from pathlib import Path
+from collections import defaultdict
+
+ROOT = Path(__file__).parent.parent.parent
+README_FILE = ROOT / "README.md"
+MD_DIR = ROOT / "md"
+
+
+def count_books_in_md_file(md_file: Path) -> int:
+ """统计md文件中的书籍数量"""
+ try:
+ content = md_file.read_text(encoding='utf-8')
+ # 计算表格行数(排除表头)
+ lines = content.split('\n')
+ count = 0
+ in_table = False
+ for line in lines:
+ if '| 书名' in line or '书名 |' in line:
+ in_table = True
+ continue
+ if in_table and line.strip().startswith('|') and '---' not in line:
+ # 检查是否是数据行(包含下载链接)
+ if '[下载](' in line:
+ count += 1
+ return count
+ except Exception as e:
+ print(f"⚠️ 读取文件失败 {md_file}: {e}")
+ return 0
+
+
+def get_all_categories() -> dict:
+ """获取所有分类及其书籍数量"""
+ categories = {}
+
+ if not MD_DIR.exists():
+ print(f"⚠️ md目录不存在: {MD_DIR}")
+ return categories
+
+ md_files = list(MD_DIR.glob("*.md"))
+
+ # 排除热门分类.md文件本身
+ md_files = [f for f in md_files if f.name != "热门分类.md"]
+
+ for md_file in md_files:
+ category = md_file.stem # 去掉.md扩展名
+ count = count_books_in_md_file(md_file)
+ if count > 0:
+ categories[category] = count
+
+ return categories
+
+
+def generate_hot_categories_section(categories: dict) -> str:
+ """生成热门分类章节内容"""
+ # 按书籍数量排序
+ sorted_categories = sorted(categories.items(), key=lambda x: x[1], reverse=True)
+
+ lines = []
+ lines.append("## 🔥 热门分类")
+ lines.append("")
+
+ # 每行8个标签
+ items_per_line = 8
+ for i in range(0, len(sorted_categories), items_per_line):
+ batch = sorted_categories[i:i + items_per_line]
+ line_items = []
+
+ for category, count in batch:
+ link = f"- [{category}({count})](md/{category}.md)"
+ line_items.append(link)
+
+ # 用 | 分隔,每行8个
+ line = " | ".join(line_items)
+ lines.append(line)
+
+ return '\n'.join(lines)
+
+
+def update_readme():
+ """更新README.md中的热门分类章节"""
+ if not README_FILE.exists():
+ print(f"❌ README.md不存在: {README_FILE}")
+ return False
+
+ # 读取README内容
+ content = README_FILE.read_text(encoding='utf-8')
+
+ # 获取所有分类
+ print("📊 正在统计分类...")
+ categories = get_all_categories()
+ print(f"✅ 找到 {len(categories)} 个分类")
+
+ if not categories:
+ print("⚠️ 未找到任何分类,跳过更新")
+ return False
+
+ # 生成新的热门分类章节
+ new_section = generate_hot_categories_section(categories)
+
+ # 查找并替换"热门分类"章节
+ # 匹配从 "## 🔥 热门分类" 开始到下一个 "##" 或文件结尾
+ # 使用更宽松的匹配:允许不同的空行数量
+ pattern = r'(## 🔥 热门分类\s*\n\s*\n)(.*?)(?=\n\s*## |\Z)'
+
+ match = re.search(pattern, content, re.DOTALL | re.MULTILINE)
+ if match:
+ # 替换匹配的内容
+ new_content = re.sub(pattern, r'\1' + new_section, content, flags=re.DOTALL | re.MULTILINE)
+
+ # 写入文件
+ README_FILE.write_text(new_content, encoding='utf-8')
+ print(f"✅ README.md已更新")
+ print(f" - 分类数量: {len(categories)}")
+ print(f" - 总书籍数: {sum(categories.values())}")
+ return True
+ else:
+ print("⚠️ 未找到'热门分类'章节,无法更新")
+ return False
+
+
+if __name__ == "__main__":
+ print("=" * 80)
+ print("📝 更新README.md热门分类章节")
+ print("=" * 80)
+ print()
+
+ success = update_readme()
+
+ if success:
+ print("\n✅ 更新完成!")
+ else:
+ print("\n❌ 更新失败!")
+ exit(1)
diff --git "a/\344\273\243\347\240\201\345\256\211\345\205\250\346\243\200\346\237\245\346\212\245\345\221\212.md" "b/\344\273\243\347\240\201\345\256\211\345\205\250\346\243\200\346\237\245\346\212\245\345\221\212.md"
new file mode 100644
index 0000000..eabdbe2
--- /dev/null
+++ "b/\344\273\243\347\240\201\345\256\211\345\205\250\346\243\200\346\237\245\346\212\245\345\221\212.md"
@@ -0,0 +1,230 @@
+# 代码安全检查报告
+
+**检查时间**: 2024年
+**检查范围**: ebook-treasure-chest 项目
+
+## 🔴 严重问题
+
+### 1. XSS(跨站脚本攻击)漏洞风险
+
+**位置**: `docs/search.js`
+
+**问题描述**:
+- `highlightText` 函数(第74-78行)和 `renderResults` 函数(第80-164行)使用了 `innerHTML` 直接插入 HTML 内容
+- 虽然书籍数据来自 JSON 文件,但搜索关键词是用户输入的,在构建正则表达式和插入 HTML 时存在安全风险
+- 如果 JSON 数据被污染或用户输入特殊字符,可能导致 XSS 攻击
+
+**风险等级**: 🔴 高
+
+**问题代码**:
+```javascript
+// 第74-78行
+function highlightText(text, keyword) {
+ if (!keyword) return text;
+ const regex = new RegExp(`(${keyword})`, 'gi'); // 未转义特殊字符
+ return text.replace(regex, '<mark>$1</mark>'); // 未转义 HTML
+}
+
+// 第119行
+div.innerHTML = `...${highlightedTitle}...`; // 直接使用 innerHTML
+```
+
+**修复建议**:
+1. 对用户输入和数据进行 HTML 转义
+2. 使用 `textContent` 或 `createElement` 代替 `innerHTML`
+3. 转义正则表达式特殊字符
+
+**修复示例**:
+```javascript
+function escapeHtml(text) {
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
+function escapeRegex(str) {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function highlightText(text, keyword) {
+ if (!keyword) return escapeHtml(text);
+ const escapedKeyword = escapeRegex(keyword);
+ const regex = new RegExp(`(${escapedKeyword})`, 'gi');
+ return escapeHtml(text).replace(regex, '<mark>$1</mark>');
+}
+```
+
+---
+
+### 2. 正则表达式注入风险
+
+**位置**: `docs/search.js` 第76行
+
+**问题描述**:
+- `highlightText` 函数直接使用用户输入的 `keyword` 构建正则表达式
+- 如果用户输入包含正则表达式特殊字符(如 `.*+?^${}()|[\]\\`),可能导致:
+ - 正则表达式错误
+ - 性能问题(ReDoS 攻击)
+ - 意外的匹配结果
+
+**风险等级**: 🟡 中
+
+**修复建议**:
+在构建正则表达式前转义特殊字符(见上面的修复示例)
+
+---
+
+## 🟡 中等问题
+
+### 3. 文件名长度限制可能不足
+
+**位置**: `scripts/sync/test_batch_sync.py` 第53-75行
+
+**问题描述**:
+- `sanitize_filename` 函数限制文件名为 200 个字符
+- 在某些文件系统中,路径总长度可能超过限制
+- 没有检查最终文件路径的总长度
+
+**风险等级**: 🟡 低
+
+**修复建议**:
+```python
+def sanitize_filename(filename: str, max_length: int = 200) -> str:
+ # ... 现有代码 ...
+
+ # 限制长度(考虑文件扩展名)
+ if len(filename) > max_length:
+ filename = filename[:max_length]
+
+ # 确保最终路径不会太长
+ # 可以添加路径总长度检查
+ return filename or "未命名"
+```
+
+---
+
+### 4. 错误处理可以改进
+
+**位置**: 多个文件
+
+**问题描述**:
+- 某些异常被静默捕获(如 `parse_book_detail_enhanced.py` 第265行)
+- 错误信息不够详细,难以调试
+- 某些网络请求没有重试机制
+
+**风险等级**: 🟡 低
+
+**修复建议**:
+- 添加更详细的错误日志
+- 对于关键操作,添加重试机制
+- 区分不同类型的错误(网络错误、解析错误等)
+
+---
+
+### 5. 硬编码的超时时间
+
+**位置**: 多个文件
+
+**问题描述**:
+- 网络请求的超时时间硬编码为 10 秒或 5 秒
+- 没有根据实际情况调整
+
+**风险等级**: 🟢 低
+
+**修复建议**:
+- 将超时时间提取为配置常量
+- 根据不同的操作类型设置不同的超时时间
+
+---
+
+## 🟢 轻微问题
+
+### 6. 代码重复
+
+**位置**: 多个文件
+
+**问题描述**:
+- HTTP headers 定义在多处重复
+- 可以提取为常量或函数
+
+**风险等级**: 🟢 低
+
+**修复建议**:
+```python
+def get_default_headers():
+ return {
+ 'User-Agent': 'Mozilla/5.0 ...',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
+ # ...
+ }
+```
+
+---
+
+### 7. 缺少输入验证
+
+**位置**: `scripts/sync/sync_all_books.py`
+
+**问题描述**:
+- `--max-id` 和 `--start-id` 参数没有验证范围
+- 如果输入负数或过大的值,可能导致问题
+
+**风险等级**: 🟢 低
+
+**修复建议**:
+```python
+parser.add_argument('--max-id', type=int, help='...')
+# 添加验证
+if args.max_id and args.max_id < 1:
+ parser.error("--max-id 必须大于 0")
+```
+
+---
+
+## ✅ 做得好的地方
+
+1. **敏感信息保护**:
+ - 使用 GitHub Secrets 存储敏感配置(`BOOK_SITE_DOMAIN`)
+ - 在生成 MD 文件时过滤敏感域名链接
+
+2. **文件名安全**:
+ - `sanitize_filename` 函数清理了不合法字符
+ - 防止路径遍历攻击
+
+3. **错误处理**:
+ - 大部分关键操作都有 try-catch
+ - 有适当的错误提示
+
+4. **代码组织**:
+ - 代码结构清晰
+ - 有适当的注释
+
+---
+
+## 📋 修复优先级
+
+1. **立即修复** (🔴):
+ - XSS 漏洞(问题 #1)
+ - 正则表达式注入(问题 #2)
+
+2. **尽快修复** (🟡):
+ - 文件名长度检查(问题 #3)
+ - 改进错误处理(问题 #4)
+
+3. **建议修复** (🟢):
+ - 代码重构(问题 #6, #7)
+ - 配置优化(问题 #5)
+
+---
+
+## 🔍 其他建议
+
+1. **添加单元测试**: 特别是对于安全相关的函数(如 `sanitize_filename`, `highlightText`)
+2. **代码审查**: 定期进行安全代码审查
+3. **依赖检查**: 定期检查依赖包的安全漏洞
+4. **CSP 策略**: 如果可能,添加 Content Security Policy 头
+
+---
+
+**报告生成时间**: 2024年
+**检查工具**: 手动代码审查