1. 项目背景与核心价值最近在整理技术文档时发现一个痛点很多优质的技术文档站点会突然关闭或改版导致之前收藏的链接失效。更麻烦的是有些文档内容需要以完整长图形式保存便于分享或打印。市面上的网页保存工具要么功能单一要么操作复杂于是决定自己用Python开发一个轻量级解决方案。这个工具的核心功能很简单将指定文档站点生成完整快照包括HTML、CSS、JS等资源同时自动生成整个页面的无缝长截图支持定时自动归档和版本对比相比传统截图工具这个方案有三大优势完整保留原始样式和交互元素如可折叠目录长图自动拼接无需手动滚动截图支持增量更新和差异对比2. 技术方案选型2.1 核心组件对比经过技术调研最终确定以下技术栈组合功能需求可选方案最终选择选择理由网页渲染Selenium/PlaywrightPlaywright更快的渲染速度原生支持无头浏览器和PDF/截图生成长图拼接Puppeteer/PillowPlaywrightPillowPlaywright负责分块截图Pillow处理图像合并兼容性更好资源下载requests/scrapyrequestsparsel轻量级组合parsel支持XPath和CSS选择器定时任务APScheduler/crontabAPScheduler纯Python方案跨平台兼容差异对比difflib/jsondiffdhashImageChops图像哈希对比像素级差异分析更适合视觉化内容2.2 关键技术实现路径整个处理流程分为四个阶段初始化阶段使用Playwright启动Chromium浏览器实例设置1280px的固定视窗宽度保证排版一致性注入自定义CSS强制显示所有折叠内容解决动态加载问题资源抓取阶段主HTML下载使用requestsretry机制应对网络波动静态资源采用异步下载器aiohttp实现URL规范化处理解决相对路径问题长图生成阶段通过page.evaluate()获取页面实际高度按2000px高度分块截图避免内存溢出用Pillow的Image.paste()进行垂直拼接添加页眉页脚元信息URL时间戳版本管理阶段使用SQLite存储抓取元数据文件存储采用{domain}/{date}/的目录结构差异对比采用感知哈希dhash算法3. 详细实现步骤3.1 环境准备推荐使用Python 3.8环境依赖安装pip install playwright pillow requests parsel apscheduler numpy playwright install # 安装浏览器驱动3.2 核心代码实现网页快照模块async def save_snapshot(url, output_dir): async with async_playwright() as p: browser await p.chromium.launch() context await browser.new_context(viewport{width:1280,height:800}) page await context.new_page() # 拦截静态资源请求 async def handle_route(route): await route.continue_() resource await route.request.response() if resource: save_resource(await resource.body(), route.request.url) await page.route(**/*, handle_route) await page.goto(url, wait_untilnetworkidle) await page.evaluate(() { // 强制展开所有折叠内容 document.querySelectorAll([aria-expandedfalse]).forEach(el el.click()); }) # 保存主HTML html await page.content() with open(f{output_dir}/index.html, w) as f: f.write(html) await browser.close()长图生成模块def capture_fullpage(url, output_path): with sync_playwright() as p: browser p.chromium.launch() page browser.new_page(viewport{width:1280, height:800}) page.goto(url, wait_untilnetworkidle) # 获取页面实际高度 total_height page.evaluate(() document.body.scrollHeight) viewport_height page.viewport_size[height] images [] for y in range(0, total_height, viewport_height): # 分块截图 image_path f/tmp/part_{y}.png page.evaluate(fwindow.scrollTo(0, {y})) page.screenshot(pathimage_path, clip{ x:0, y:0, width:1280, height:min(viewport_height, total_height-y) }) images.append(Image.open(image_path)) # 垂直拼接 full_image Image.new(RGB, (1280, total_height)) y_offset 0 for img in images: full_image.paste(img, (0, y_offset)) y_offset img.size[1] img.close() full_image.save(output_path) browser.close()3.3 定时任务集成from apscheduler.schedulers.blocking import BlockingScheduler def job(url, output_base): date_str datetime.now().strftime(%Y%m%d) output_dir f{output_base}/{urlparse(url).netloc}/{date_str} os.makedirs(output_dir, exist_okTrue) asyncio.run(save_snapshot(url, output_dir)) capture_fullpage(url, f{output_dir}/fullpage.png) scheduler BlockingScheduler() scheduler.add_job(job, cron, args[target_url, output_path], day_of_week0-6, hour3) # 每天凌晨3点执行 scheduler.start()4. 实战优化技巧4.1 性能调优方案并发控制限制同时打开的浏览器实例数建议≤3静态资源下载使用Semaphore控制并发量sem asyncio.Semaphore(5) async with sem: await download_resource(url)缓存利用对静态资源URL计算MD5作为文件名实现304 Not Modified检测if os.path.exists(cache_path): with open(cache_path, rb) as f: etag hashlib.md5(f.read()).hexdigest() headers {If-None-Match: etag}智能等待策略# 混合等待条件 await page.wait_for_selector(article, stateattached) await page.wait_for_function( () document.readyState complete window.jQuery ! undefined jQuery.active 0 )4.2 常见问题解决方案问题1动态内容加载不全解决方案注入强制渲染脚本// 滚动触发懒加载 window.scrollBy(0, 100); setTimeout(() { window.scrollBy(0, -100); }, 500);问题2截图出现空白间隙解决方案调整滚动步长与截图高度比例scroll_step viewport_height - 50 # 保留50px重叠区域 for y in range(0, total_height, scroll_step): ...问题3反爬虫机制拦截解决方案伪装常规浏览器特征context await browser.new_context( user_agentMozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36..., localezh-CN, timezone_idAsia/Shanghai )5. 扩展应用场景5.1 企业级增强方案对于团队协作场景可以扩展以下功能API服务化from fastapi import FastAPI app FastAPI() app.post(/archive) async def create_archive(url: str): task_id str(uuid.uuid4()) asyncio.create_task(background_archive(url, task_id)) return {task_id: task_id}可视化对比def generate_diff(old_img, new_img): diff ImageChops.difference(old_img, new_img) diff diff.convert(L).point(lambda x: 255 if x 30 else 0) return diff自动生成报告def generate_report(url, changes): pdf FPDF() pdf.add_page() pdf.set_font(Arial, size12) pdf.cell(200, 10, txtfArchiving Report for {url}, ln1) for change in changes: pdf.cell(200, 10, txtchange, ln1) pdf.output(report.pdf)5.2 个人知识管理集成Obsidian插件方案module.exports async function(url) { const {execSync} require(child_process) const output execSync(python archiver.py ${url}) this.app.vault.create(Archives/${Date.now()}.md, output) }Notion自动化集成from notion_client import Client notion Client(authos.environ[NOTION_TOKEN]) def upload_to_notion(url, img_path): with open(img_path, rb) as f: file notion.upload_file(f) notion.pages.create( parent{database_id: DB_ID}, properties{Title: {title: [{text: {content: url}}]}}, children[{type: image, image: {file: {url: file.url}}}] )6. 维护与迭代建议监控指标设计成功率监控记录每次抓取的HTTP状态码质量检测通过OCR识别截图中的404等错误文本性能统计记录各阶段耗时网络请求、渲染、截图等异常处理机制async def safe_capture(url): try: return await capture_page(url) except PlaywrightTimeoutError: await page.reload() return await capture_page(url) except Exception as e: send_alert(fCapture failed: {str(e)}) raise自动化测试方案pytest.mark.asyncio async def test_snapshot(): test_url https://example.com await save_snapshot(test_url, /tmp/test) assert os.path.exists(/tmp/test/index.html) assert os.path.getsize(/tmp/test/index.html) 1024这个项目在实际使用中给我最大的启示是自动化归档不仅要考虑技术实现更需要设计合理的内容组织结构。我现在采用域名/年/月-日的目录结构配合SQLite记录元数据半年下来已经建立了可快速检索的万级文档库。最近新增的视觉差异对比功能帮助我发现了多个技术文档的隐蔽更新点这些都是在原始需求之外获得的意外价值。