python脚本批量导出ZEEKLOG里的文章

python脚本批量导出ZEEKLOG里的文章

一 导出全部已发布文章

首先,需要在本地安装3.8版本以上的python,安装python步骤

检查是否安装成功

pip3 --version 

安装后执行

pip3 install requests beautifulsoup4 markdownify 

新建脚本,脚本名字随意,这里是:ZEEKLOG_downloader.py

脚本内容如下:

# -*- coding: utf-8 -*-import os import re import requests import time from bs4 import BeautifulSoup from markdownify import markdownify as md from urllib.parse import urlparse, unquote import hashlib from pathlib import Path # ================== 配置区 ================== ZEEKLOG_USERNAME ="qq_33417321"# ←←← 修改为你想下载的用户名 SAVE_DIR = Path("ZEEKLOG_articles")# 文章保存根目录(自动跨平台) HEADERS ={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36","Referer":"https://blog.ZEEKLOG.net/"}defsanitize_filename(name:str)->str:"""清理文件名,移除 Windows 非法字符和‘原创’字样""" name = name.replace("原创","").strip()# 移除 Windows 非法字符 name = re.sub(r'[\\/*?:"<>|\r\n]',"_", name)return name or"untitled"defget_article_list(username):"""获取博主文章列表(标题和URL)""" url =f"https://blog.ZEEKLOG.net/{username}/article/list" articles =[] page =1whileTrue: response = requests.get(f"{url}/{page}", headers=HEADERS) soup = BeautifulSoup(response.text,'html.parser') items = soup.select(".article-list .article-item-box")ifnot items:breakfor item in items: title_elem = item.select_one("h4 a")ifnot title_elem:continue title = title_elem.text.strip() link = title_elem["href"] articles.append({"title": title,"url": link}) page +=1 time.sleep(1)return articles defdownload_image(img_url, save_path: Path):"""下载单张图片到本地"""try: img_headers = HEADERS.copy() img_headers["Accept"]="image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8" response = requests.get(img_url, headers=img_headers, stream=True, timeout=30)if response.status_code ==200: save_path.parent.mkdir(parents=True, exist_ok=True)withopen(save_path,'wb')as f:for chunk in response.iter_content(chunk_size=8192):if chunk: f.write(chunk)returnTrueelse:print(f"图片下载失败(状态码:{response.status_code}):{img_url}")returnFalseexcept Exception as e:print(f"图片下载异常:{img_url},错误:{str(e)}")returnFalsedefget_image_extension(img_url):"""从URL中获取图片扩展名""" parsed_url = urlparse(img_url) path = parsed_url.path.lower() extensions =['.jpg','.jpeg','.png','.gif','.webp','.bmp','.svg']for ext in extensions:if ext in path:return ext return'.jpg'defprocess_images_in_content(content, article_title):"""处理内容中的图片,下载并替换为本地路径""" soup = BeautifulSoup(content,'html.parser') img_tags = soup.find_all('img')ifnot img_tags:return content # 清理文章标题用于路径 safe_title = sanitize_filename(article_title) global_image_dir = SAVE_DIR /"images" article_image_dir = global_image_dir / safe_title for img in img_tags: img_url = img.get('src','')ifnot img_url:continue# 处理协议相对路径if img_url.startswith('//'): img_url ='https:'+ img_url elifnot img_url.startswith(('http://','https://')):continue# 跳过无法处理的相对路径try: img_hash = hashlib.md5(img_url.encode()).hexdigest()[:8] img_ext = get_image_extension(img_url) img_filename =f"{img_hash}{img_ext}" local_img_path = article_image_dir / img_filename # Markdown 中使用正斜杠(/),兼容所有平台 md_img_path =f"./images/{safe_title}/{img_filename}"ifnot local_img_path.exists():print(f" 下载图片:{img_filename}")if download_image(img_url, local_img_path): img['src']= md_img_path else:print(f" 图片下载失败,保留原链接:{img_url}")else: img['src']= md_img_path except Exception as e:print(f" 处理图片时出错:{img_url},错误:{str(e)}")continuereturnstr(soup)defdownload_article(url, article_title):"""下载单篇文章,处理图片后转为Markdown"""try: response = requests.get(url, headers=HEADERS, timeout=30) soup = BeautifulSoup(response.text,'html.parser') content = soup.select_one("article")ifnot content:print(f" 未找到文章内容")returnNone processed_content = process_images_in_content(str(content), article_title) markdown_content = md(processed_content)return markdown_content except Exception as e:print(f" 下载文章时出错:{str(e)}")returnNonedefsave_to_markdown(title, content, save_dir: Path):"""保存Markdown文件""" save_dir.mkdir(parents=True, exist_ok=True) safe_title = sanitize_filename(title) filename = save_dir /f"{safe_title}.md"withopen(filename,"w", encoding="utf-8")as f: f.write(f"# {title}\n\n") f.write(content)print(f" 已保存:{filename}")return filename if __name__ =="__main__":print("开始获取文章列表...") articles = get_article_list(ZEEKLOG_USERNAME)print(f"找到 {len(articles)} 篇文章") success_count =0 fail_count =0for i, article inenumerate(articles,1): title = article["title"] url = article["url"]print(f"\n[{i}/{len(articles)}] 处理文章:{title}") content = download_article(url, title)if content: save_to_markdown(title, content, SAVE_DIR) success_count +=1else:print(f" 文章下载失败:{title}") fail_count +=1 time.sleep(2)print(f"\n处理完成!成功:{success_count}篇,失败:{fail_count}篇")print(f"文章保存在:{SAVE_DIR.resolve()}")print("图片保存在:./images/ 目录下,Markdown文件可离线查看")

其中,脚本里ZEEKLOG_USERNAME的值,改为你要获取的ZEEKLOG的用户名

获取用户名:点击作者头像后,链接里的这个值就是用户名(红框里的内容)

在这里插入图片描述

执行脚本

python ZEEKLOG_downloader.py 

执行日志入下:

在这里插入图片描述

由于要下载ZEEKLOG文章里的图片,所以很慢,静静等待即可。下载过程中,会在脚本所在目录生成一个ZEEKLOG_articles文件夹,里边是md文件以及存md里的图片的文件夹。

在这里插入图片描述

二 导出指定日期后的文章

上边的脚本,一次性导出了所有已发布的文章,但是有时候我们的文章太多,每次备份不需要全部导出,只导出指定时间以后的文章,那么使用如下脚本即可,如脚本名为new.py,内容如下

# -*- coding: utf-8 -*-import os import re import requests import time from bs4 import BeautifulSoup from markdownify import markdownify as md from urllib.parse import urlparse, unquote import hashlib from pathlib import Path from datetime import datetime # ================== 配置区 ================== ZEEKLOG_USERNAME ="qq_33417321"# ←←← 修改为你想下载的用户名 SAVE_DIR = Path("ZEEKLOG_articles")# 文章保存根目录(自动跨平台)# ⬇️ 新增:设置最小发布日期(含) MIN_PUBLISH_DATE = datetime(2026,2,7)# 只下载 2026年2月1日及之后的文章 HEADERS ={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36","Referer":"https://blog.ZEEKLOG.net/"}defsanitize_filename(name:str)->str:"""清理文件名,移除 Windows 非法字符和‘原创’字样""" name = name.replace("原创","").strip() name = re.sub(r'[\\/*?:"<>|\r\n]',"_", name)return name or"untitled"defparse_publish_date(date_str:str)-> datetime |None:"""尝试解析 ZEEKLOG 日期字符串,支持 '2025-06-15 10:30:00' 或 '2025-06-15' 等""" date_str = date_str.strip()for fmt in["%Y-%m-%d %H:%M:%S",# 带秒,如 2025-06-15 10:30:09"%Y-%m-%d %H:%M",# 不带秒,如 2025-06-15 10:30"%Y-%m-%d"# 只有日期,如 2025-06-15]:try:return datetime.strptime(date_str, fmt)except ValueError:continueprint(f" 无法解析日期:{date_str}")returnNonedefget_article_list(username, min_date=None):"""获取博主文章列表(标题、URL、发布时间),可选按 min_date 过滤""" url =f"https://blog.ZEEKLOG.net/{username}/article/list" articles =[] page =1 early_stop =Falsewhilenot early_stop:print(f" 正在抓取第 {page} 页...") response = requests.get(f"{url}/{page}", headers=HEADERS) soup = BeautifulSoup(response.text,'html.parser') items = soup.select(".article-list .article-item-box")ifnot items:break current_page_has_valid =False# 当前页是否有满足条件的文章for item in items: title_elem = item.select_one("h4 a") date_elem = item.select_one(".date")# ZEEKLOG 通常用 .date 类表示发布时间ifnot title_elem:continue title = title_elem.text.strip() link = title_elem["href"] pub_date =Noneif date_elem: raw_date = date_elem.text.strip() pub_date = parse_publish_date(raw_date)# 如果设置了最小日期,且文章发布时间早于该日期,则跳过if min_date and pub_date and pub_date < min_date:continue# 如果发布时间未知但设置了 min_date,保守起见也跳过(或可选择保留)if min_date andnot pub_date:print(f" 警告:无法获取文章 [{title}] 的发布时间,跳过(因设置了日期过滤)")continue articles.append({"title": title,"url": link,"publish_date": pub_date }) current_page_has_valid =True# 如果当前页没有任何有效文章(全部早于 min_date),可提前终止if min_date andnot current_page_has_valid and page >1:print(" 后续页面文章均早于指定日期,停止翻页。") early_stop =True page +=1 time.sleep(1)return articles # ========== 以下函数保持不变 ==========defdownload_image(img_url, save_path: Path):try: img_headers = HEADERS.copy() img_headers["Accept"]="image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8" response = requests.get(img_url, headers=img_headers, stream=True, timeout=30)if response.status_code ==200: save_path.parent.mkdir(parents=True, exist_ok=True)withopen(save_path,'wb')as f:for chunk in response.iter_content(chunk_size=8192):if chunk: f.write(chunk)returnTrueelse:print(f"图片下载失败(状态码:{response.status_code}):{img_url}")returnFalseexcept Exception as e:print(f"图片下载异常:{img_url},错误:{str(e)}")returnFalsedefget_image_extension(img_url): parsed_url = urlparse(img_url) path = parsed_url.path.lower() extensions =['.jpg','.jpeg','.png','.gif','.webp','.bmp','.svg']for ext in extensions:if ext in path:return ext return'.jpg'defprocess_images_in_content(content, article_title): soup = BeautifulSoup(content,'html.parser') img_tags = soup.find_all('img')ifnot img_tags:return content safe_title = sanitize_filename(article_title) global_image_dir = SAVE_DIR /"images" article_image_dir = global_image_dir / safe_title for img in img_tags: img_url = img.get('src','')ifnot img_url:continueif img_url.startswith('//'): img_url ='https:'+ img_url elifnot img_url.startswith(('http://','https://')):continuetry: img_hash = hashlib.md5(img_url.encode()).hexdigest()[:8] img_ext = get_image_extension(img_url) img_filename =f"{img_hash}{img_ext}" local_img_path = article_image_dir / img_filename md_img_path =f"./images/{safe_title}/{img_filename}"ifnot local_img_path.exists():print(f" 下载图片:{img_filename}")if download_image(img_url, local_img_path): img['src']= md_img_path else:print(f" 图片下载失败,保留原链接:{img_url}")else: img['src']= md_img_path except Exception as e:print(f" 处理图片时出错:{img_url},错误:{str(e)}")continuereturnstr(soup)defdownload_article(url, article_title):try: response = requests.get(url, headers=HEADERS, timeout=30) soup = BeautifulSoup(response.text,'html.parser') content = soup.select_one("article")ifnot content:print(f" 未找到文章内容")returnNone processed_content = process_images_in_content(str(content), article_title) markdown_content = md(processed_content)return markdown_content except Exception as e:print(f" 下载文章时出错:{str(e)}")returnNonedefsave_to_markdown(title, content, save_dir: Path): save_dir.mkdir(parents=True, exist_ok=True) safe_title = sanitize_filename(title) filename = save_dir /f"{safe_title}.md"withopen(filename,"w", encoding="utf-8")as f: f.write(f"# {title}\n\n") f.write(content)print(f" 已保存:{filename}")return filename # ========== 主程序入口 ==========if __name__ =="__main__":print("开始获取文章列表...") articles = get_article_list(ZEEKLOG_USERNAME, min_date=MIN_PUBLISH_DATE)print(f"找到 {len(articles)} 篇符合条件的文章(发布日期 ≥ {MIN_PUBLISH_DATE.strftime('%Y-%m-%d')})") success_count =0 fail_count =0for i, article inenumerate(articles,1): title = article["title"] url = article["url"] pub_date = article.get("publish_date") date_str = pub_date.strftime("%Y-%m-%d")if pub_date else"未知"print(f"\n[{i}/{len(articles)}] 处理文章:{title} (发布于 {date_str})") content = download_article(url, title)if content: save_to_markdown(title, content, SAVE_DIR) success_count +=1else:print(f" 文章下载失败:{title}") fail_count +=1 time.sleep(2)print(f"\n处理完成!成功:{success_count}篇,失败:{fail_count}篇")print(f"文章保存在:{SAVE_DIR.resolve()}")print("图片保存在:./images/ 目录下,Markdown文件可离线查看")

记得修改MIN_PUBLISH_DATE 里的开始日期。之后执行脚本后,下载下来就是指定日期后的文章了。

Read more

GTC2026前瞻(二)Agentic AI 与开源模型篇+(三)Physical AI 与机器人篇

GTC2026前瞻(二)Agentic AI 与开源模型篇+(三)Physical AI 与机器人篇

(二)Agentic AI 与开源模型篇 Agentic AI与开源模型:英伟达想定义的,不只是“更聪明的模型”,而是“能持续工作的数字劳动力” 如果说过去两年的大模型竞赛,核心问题还是“谁能生成更像人的答案”,那么到了 GTC 2026,问题已经明显变了。英伟达把 Agentic AI 直接列为大会四大核心主题之一,官方对这一主题的定义也很明确:重点不再是单轮问答,而是让 AI agent 能够推理、规划、检索并执行动作,最终把企业数据转化为可投入生产的“数字劳动力”。这说明,Agentic AI 在英伟达的语境里,已经不是一个前沿概念,而是下一阶段 AI 商业化的主战场。(NVIDIA) 一、GTC 2026真正的变化,是 AI 开始从“会回答”走向“会做事”

By Ne0inhk

硬件-电源-VR多相电源深入解析

1. 引言 一块高性能服务器主板的CPU插槽周围,总是簇拥着一排排整齐的、覆盖着金属散热片的“小方块”。它们就属于VR多相电源的一部分,VR多相电源如同CPU的“专用心脏”,负责将来自电源的“粗犷”能量,转化为CPU所能接受的“精细”养分。本文主要介绍Buck多相电源。 2. VRM是什么?为什么需要“多相”? 2.1 VRM的核心使命:精准的“能量转换师” VRM,全称 Voltage Regulator Module(电压调节模块),其核心任务只有一个:将来自一次电源的电压(如+12V),高效、精准地转换为CPU、GPU等核心芯片所需的低电压(如0.8V~1.3V)和大电流(可达数百A)。 如果让数百安培的电流直接以1V电压从机箱电源传输到CPU,线路损耗将是灾难性的。因此,必须在CPU边上就近进行高效电压转换,这就是VRM存在的根本原因。 2.

By Ne0inhk
AstrBot+NapCat 一键部署 5 分钟搞定智能 QQ 机器人!cpolar解决公网访问 :cpolar 内网穿透实验室第 777 个成功挑战

AstrBot+NapCat 一键部署 5 分钟搞定智能 QQ 机器人!cpolar解决公网访问 :cpolar 内网穿透实验室第 777 个成功挑战

这篇教程会带你用最简单的方式:**只用一份 docker-compose,一次命令,5 分钟以内完成 AstrBot + NapCat 部署,把 DeepSeekAI 接入你的 QQ。**AstrBot 本身就是为 AI 而生的现代化机器人框架,插件丰富、支持 DeepSeek/OpenAI 等大模型、带 WebUI、可扩展性强,真正做到"搭好就能用"。照着做,你马上就能拥有属于自己的 QQ AI 机器人。 1 项目介绍 1.1 AstrBot是什么? GitHub 仓库:https://github.com/AstrBotDevs/AstrBot AstrBot 是一个专为 AI 大模型设计的开源聊天机器人框架,

By Ne0inhk
从0到1打造RISC-V智能家居中控:硬件+固件+通信全链路实战

从0到1打造RISC-V智能家居中控:硬件+固件+通信全链路实战

👋 大家好,欢迎来到我的技术博客! 📚 在这里,我会分享学习笔记、实战经验与技术思考,力求用简单的方式讲清楚复杂的问题。 🌱 无论你是刚入门的新手,还是正在进阶的开发者,希望你都能有所收获! 文章目录 * 从0到1打造RISC-V智能家居中控:硬件+固件+通信全链路实战 🏠💡 * 为什么选择RISC-V?🤔 * 系统整体架构概览 🧩 * 第一步:硬件选型与电路搭建 🔌 * 主控芯片选择 * 外设连接 * 第二步:开发环境搭建 🛠️ * 安装步骤(以Ubuntu为例) * 第三步:裸机驱动开发(Bare Metal)⚡ * 示例1:DHT11温湿度读取(Bit-banging) * 示例2:BH1750光照传感器(I2C) * 第四步:引入FreeRTOS实现多任务调度 🔄 * 第五步:Wi-Fi连接与MQTT通信 ☁️📡 * 连接Wi-Fi * MQTT客户端(使用esp-mqtt库) * 第六步:BLE本地控制(无需Wi-Fi)📱

By Ne0inhk