Compare commits

..
3 Commits
6 changed files with 98 additions and 22 deletions
+2 -2
View File
@@ -49,12 +49,12 @@
- 可启用/停用调度,自动计算下次执行时间;到点自动开跑,跑完自动计算下一次 - 可启用/停用调度,自动计算下次执行时间;到点自动开跑,跑完自动计算下一次
### 4. 自动爬取模式 ### 4. 自动爬取模式
给定一个起始网址,系统自动从页面里发现链接、按规则筛选后 BFS 爬取: 给定一个起始网址,系统**持续递归**爬取:爬取页面 → 自动发现符合规则的链接 → 继续爬取 → 继续发现……直到**无新链接可爬**时自动结束。
- **🧪 试爬取**:先用起始网址试跑一次,展示规则筛选后的链接清单(将爬取哪些、排除哪些及原因),确认规则符合预期后再正式开爬 - **🧪 试爬取**:先用起始网址试跑一次,展示规则筛选后的链接清单(将爬取哪些、排除哪些及原因),确认规则符合预期后再正式开爬
- **最大页数(安全上限)**:无深度限制,但达到页数上限自动停止,防止动态无限链接的站点失控
- **包含规则**:只爬包含指定子串(或正则)的链接 - **包含规则**:只爬包含指定子串(或正则)的链接
- **排除规则**:跳过匹配的链接(如 login、/tag/ - **排除规则**:跳过匹配的链接(如 login、/tag/
- **仅同域名**:限制在起始网站内 - **仅同域名**:限制在起始网站内
- **最大页数 / 最大深度**:控制爬取规模
- 其余参数(间隔、重试、图片、通知)同批量模式 - 其余参数(间隔、重试、图片、通知)同批量模式
### 5. 资源操作信息(元数据) ### 5. 资源操作信息(元数据)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
历史爬取记录回填数据库 (幂等, 可重复执行)
用法:
python backfill.py # 回填所有任务的历史记录
python backfill.py <task_id> ... # 只回填指定任务
说明:
- 将本地 data/ 中的任务/运行/爬取结果(含成功与失败)全量写入 MySQL
- 网页内容不入库, 只写元数据; 重复执行不会产生重复记录
"""
import sys
import db
import store
if __name__ == "__main__":
ids = [a for a in sys.argv[1:] if a.strip()] or None
db.init_db()
stats = db.sync_all_history(ids)
if ids:
print(f"[backfill] 已回填 {len(ids)} 个任务: {stats}")
else:
print(f"[backfill] 已回填全部任务: {stats}")
+57 -7
View File
@@ -67,9 +67,7 @@ DDL = [
source_url VARCHAR(2000), source_url VARCHAR(2000),
depth INT, depth INT,
attempts INT DEFAULT 1, attempts INT DEFAULT 1,
html_file VARCHAR(500), base_file VARCHAR(500),
txt_file VARCHAR(500),
meta_file VARCHAR(500),
image_count INT DEFAULT 0, image_count INT DEFAULT 0,
image_files TEXT, image_files TEXT,
UNIQUE KEY uk_run_url (run_id, url(500)) UNIQUE KEY uk_run_url (run_id, url(500))
@@ -78,6 +76,17 @@ DDL = [
] ]
def _migrate(conn):
"""存量表结构迁移: 合并 html_file/txt_file/meta_file 为 base_file"""
with conn.cursor() as cur:
cur.execute("SHOW COLUMNS FROM crawl_results LIKE 'html_file'")
if cur.fetchone():
cur.execute("ALTER TABLE crawl_results ADD COLUMN base_file VARCHAR(500) NULL AFTER meta_file")
cur.execute("UPDATE crawl_results SET base_file = REPLACE(html_file, '.html', '') WHERE base_file IS NULL")
cur.execute("ALTER TABLE crawl_results DROP COLUMN html_file, DROP COLUMN txt_file, DROP COLUMN meta_file")
print("[db] 表结构迁移完成: html_file/txt_file/meta_file -> base_file")
def _conn(): def _conn():
cfg = dict(DB_CONFIG) cfg = dict(DB_CONFIG)
cfg["database"] = DB_NAME cfg["database"] = DB_NAME
@@ -100,6 +109,7 @@ def init_db():
cur.execute(f"CREATE DATABASE IF NOT EXISTS `{DB_NAME}` DEFAULT CHARACTER SET utf8mb4") cur.execute(f"CREATE DATABASE IF NOT EXISTS `{DB_NAME}` DEFAULT CHARACTER SET utf8mb4")
conn.close() conn.close()
conn = _conn() conn = _conn()
_migrate(conn)
with conn.cursor() as cur: with conn.cursor() as cur:
for ddl in DDL: for ddl in DDL:
cur.execute(ddl) cur.execute(ddl)
@@ -219,8 +229,21 @@ def upsert_run(run):
# ---------------- 爬取结果 (每页一条, 成功失败均记录) ---------------- # ---------------- 爬取结果 (每页一条, 成功失败均记录) ----------------
def _base_of(entry):
"""从结果条目提取基础文件名 (html/txt/meta 三个后缀共用同一前缀)"""
for f in (entry.get("meta_file"), entry.get("html_file"), entry.get("txt_file")):
f = f or ""
if f.endswith(".meta.json"):
return f[:-10]
if f.endswith(".html"):
return f[:-5]
if f.endswith(".txt"):
return f[:-4]
return ""
def insert_results(run, results): def insert_results(run, results):
"""批量插入爬取结果 (增量)""" """批量插入爬取结果 (增量); 文件只记基础名 base_file"""
if not results: if not results:
return return
@@ -234,7 +257,7 @@ def insert_results(run, results):
r.get("status", "FAIL"), r.get("error"), r.get("status", "FAIL"), r.get("error"),
_dt(r.get("crawl_time")), (r.get("source_url") or "")[:2000], _dt(r.get("crawl_time")), (r.get("source_url") or "")[:2000],
r.get("depth"), r.get("attempts", 1), r.get("depth"), r.get("attempts", 1),
r.get("html_file", ""), r.get("txt_file", ""), r.get("meta_file", ""), _base_of(r),
len(r.get("images", []) or []), len(r.get("images", []) or []),
_j([im.get("file") for im in (r.get("images") or [])]), _j([im.get("file") for im in (r.get("images") or [])]),
)) ))
@@ -243,8 +266,8 @@ def insert_results(run, results):
"""INSERT IGNORE INTO crawl_results """INSERT IGNORE INTO crawl_results
(run_id, task_id, mode, url, title, status, error, (run_id, task_id, mode, url, title, status, error,
crawl_time, source_url, depth, attempts, crawl_time, source_url, depth, attempts,
html_file, txt_file, meta_file, image_count, image_files) base_file, image_count, image_files)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""", VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
rows, rows,
) )
conn.close() conn.close()
@@ -262,3 +285,30 @@ def sync_run(run, persist):
insert_results(run, results[synced:]) insert_results(run, results[synced:])
run["_db_count"] = len(results) run["_db_count"] = len(results)
persist(run.get("task_id"), run) persist(run.get("task_id"), run)
# ---------------- 历史数据回填 (幂等) ----------------
def sync_all_history(task_ids=None):
"""把本地 JSON 中的历史任务/运行/结果全量回填数据库
可重复执行 (INSERT IGNORE + 唯一键去重)
task_ids: 指定只回填的任务ID列表, 默认全部
返回统计 dict
"""
import store as _store
stats = {"tasks": 0, "runs": 0, "results": 0}
for task in _store.load_tasks():
if task_ids and task["id"] not in task_ids:
continue
upsert_task(task)
stats["tasks"] += 1
for run in _store.get_runs(task["id"]):
upsert_run(run)
stats["runs"] += 1
results = run.get("results", [])
if results:
insert_results(run, results)
stats["results"] += len(results)
run["_db_count"] = len(results)
_store.save_run(task["id"], run) # 记录已同步标记, 避免运行中重复插入
return stats
+7 -3
View File
@@ -567,11 +567,11 @@ class CrawlJob:
return included return included
def _crawl_auto(self): def _crawl_auto(self):
"""自动爬取: 持续递归 爬取->发现链接->爬取... 直到无新链接可爬或达到安全上限"""
run = self.run run = self.run
auto = self.task.get("auto", {}) auto = self.task.get("auto", {})
seed = auto.get("seed_url", "") seed = auto.get("seed_url", "")
max_pages = int(auto.get("max_pages", 50) or 50) max_pages = int(auto.get("max_pages", 200) or 200) # 安全上限, 防失控
max_depth = int(auto.get("max_depth", 2) or 2)
run["progress"]["total"] = max_pages run["progress"]["total"] = max_pages
out_dir = self._resolve_out_dir() out_dir = self._resolve_out_dir()
run["out_dir"] = out_dir run["out_dir"] = out_dir
@@ -591,6 +591,7 @@ class CrawlJob:
if key in visited: if key in visited:
continue continue
if len(visited) >= max_pages: if len(visited) >= max_pages:
self._log("info", f"达到最大页数上限 {max_pages}, 停止")
break break
visited.add(key) visited.add(key)
idx += 1 idx += 1
@@ -602,7 +603,8 @@ class CrawlJob:
run["results"].append(entry) run["results"].append(entry)
self._bump_stats(entry) self._bump_stats(entry)
self._persist() self._persist()
if entry["status"] == "OK" and depth < max_depth: # 无深度限制: 只要页面爬取成功就继续发现链接, 递归直到队列为空
if entry["status"] == "OK":
for link in self._discover_links(page): for link in self._discover_links(page):
lk = normalize_url(link) lk = normalize_url(link)
if lk not in visited and lk not in queued: if lk not in visited and lk not in queued:
@@ -613,4 +615,6 @@ class CrawlJob:
finally: finally:
self._close_browser(p, browser, ctx, cookie_file) self._close_browser(p, browser, ctx, cookie_file)
run["progress"]["total"] = len(visited) run["progress"]["total"] = len(visited)
if not self._stop.is_set() and len(visited) < max_pages:
self._log("info", f"无新链接可爬, 任务结束 (共 {len(visited)} 页)")
self._persist() self._persist()
+3 -5
View File
@@ -82,7 +82,7 @@ function taskStatusBadge(t) {
const GROUPS = [ const GROUPS = [
{ key: "batch", label: "📄 批量爬取", desc: "一次性爬取指定网址列表" }, { key: "batch", label: "📄 批量爬取", desc: "一次性爬取指定网址列表" },
{ key: "scheduled", label: "⏰ 定时爬取", desc: "按间隔或 cron 表达式定时执行" }, { key: "scheduled", label: "⏰ 定时爬取", desc: "按间隔或 cron 表达式定时执行" },
{ key: "auto", label: "🤖 自动爬取", desc: "从起始网址自动发现链接并爬取" }, { key: "auto", label: "🤖 自动爬取", desc: "从起始网址自动发现链接,持续递归爬取到无新链接为止" },
]; ];
function renderTasks() { function renderTasks() {
@@ -434,8 +434,7 @@ async function openEdit(tid) {
f.elements["exclude"].value = (t.auto.exclude || []).join("\n"); f.elements["exclude"].value = (t.auto.exclude || []).join("\n");
f.elements["same_domain"].checked = t.auto.same_domain !== false; f.elements["same_domain"].checked = t.auto.same_domain !== false;
f.elements["use_regex"].checked = !!t.auto.use_regex; f.elements["use_regex"].checked = !!t.auto.use_regex;
f.elements["max_pages"].value = t.auto.max_pages ?? 50; f.elements["max_pages"].value = t.auto.max_pages ?? 200;
f.elements["max_depth"].value = t.auto.max_depth ?? 2;
} }
syncScheduleUI(); syncScheduleUI();
$("formHint").textContent = t.running $("formHint").textContent = t.running
@@ -481,8 +480,7 @@ async function submitForm(e) {
exclude: splitLines(f.elements["exclude"].value), exclude: splitLines(f.elements["exclude"].value),
same_domain: f.elements["same_domain"].checked, same_domain: f.elements["same_domain"].checked,
use_regex: f.elements["use_regex"].checked, use_regex: f.elements["use_regex"].checked,
max_pages: parseInt(f.elements["max_pages"].value) || 50, max_pages: parseInt(f.elements["max_pages"].value) || 200,
max_depth: parseInt(f.elements["max_depth"].value) || 2,
}; };
} }
if (mode === "scheduled") { if (mode === "scheduled") {
+3 -5
View File
@@ -116,7 +116,7 @@
</div> </div>
<div id="autoBox" class="hidden box"> <div id="autoBox" class="hidden box">
<div class="field"><label>起始网址 *系统将自动发现符合规则的链接并爬取</label> <div class="field"><label>起始网址 *(自动发现符合规则的链接,持续递归爬取直到无新链接可爬</label>
<div class="row2"> <div class="row2">
<input name="seed_url" placeholder="https://example.com/news" style="flex:1"> <input name="seed_url" placeholder="https://example.com/news" style="flex:1">
<button type="button" class="btn sm" id="btnProbe">🧪 试爬取</button> <button type="button" class="btn sm" id="btnProbe">🧪 试爬取</button>
@@ -132,10 +132,8 @@
<div class="field check"><label><input name="same_domain" type="checkbox" checked> 仅爬同域名</label></div> <div class="field check"><label><input name="same_domain" type="checkbox" checked> 仅爬同域名</label></div>
<div class="field check"><label><input name="use_regex" type="checkbox"> 规则按正则匹配</label></div> <div class="field check"><label><input name="use_regex" type="checkbox"> 规则按正则匹配</label></div>
</div> </div>
<div class="row2"> <div class="field"><label>最大页数(安全上限,达到后自动停止;不设深度限制,会一直递归爬取到无新链接可爬为止)</label>
<div class="field"><label>最大页数</label><input name="max_pages" type="number" value="50"></div> <input name="max_pages" type="number" value="200"></div>
<div class="field"><label>最大爬取深度</label><input name="max_depth" type="number" value="2"></div>
</div>
</div> </div>
</div> </div>
<div class="modal-foot"> <div class="modal-foot">