怎么把菜鸟教程Python栏目批量下载为本地HTML文件
详细讲解如何通过Python脚本将菜鸟教程Python栏目批量抓取并保存为本地HTML文件,涵盖章节目录解析、正文内容提取、静态样式保留及离线索引生成的完整操作与代码示例。
将菜鸟教程(RUNOOB)的 Python 栏目批量保存为本地 HTML 文件,核心思路是“解析左侧目录索引、遍历抓取各章节内容、精简提取正文 DOM 并本地持久化”。由于菜鸟教程的内容主要是通过服务端渲染生成的静态 HTML 结构,并不依赖复杂的客户端异步 JavaScript 渲染,因此只需要使用 Python 的标准请求库配合 HTML 解析器,即可高效完成整个栏目的批量抓取,并生成可完全脱机浏览的本地静态知识库。
一、准备环境与依赖库
完成本次批量下载任务,需要具备基础的 Python 3 运行环境。建议使用 Python 3.8 及以上版本。核心第三方库仅需两个:负责 HTTP 网络通信的 requests 和负责 HTML 节点解析的 beautifulsoup4。
# 在终端或命令行中执行依赖安装
pip install requests beautifulsoup4
其中,requests 用于发起网络请求并获取网页源码,而 BeautifulSoup 则提供了简洁高效的 DOM 遍历与筛选接口,能够精准抓取目录列表和剥离正文节点。
二、理解菜鸟教程的页面结构
在编写自动化抓取代码前,了解目标页面的 HTML 结构至关重要。菜鸟教程的 Python 教程首页通常为 https://www.runoob.com/python3/python3-tutorial.html。分析其网页源码可以发现两个关键结构特征:
- 左侧章节目录栏:通常位于
class="left-column"容器中。该区域包含了当前栏目所有的章节链接,每个<a>标签的文本即为章节名称,href属性则是相对路径(例如python3-intro.html)。 - 中间正文区域:教程核心内容放置在
class="article-intro"或class="article"的容器内。该节点下包含了标题、说明段落以及代码示例框。
三、分步实现批量下载
步骤 1:解析教程主目录并获取全部章节 URL
首先请求教程首页,从左侧侧边栏中找出所有章节链接。由于菜鸟教程的相对链接可能形如 python3-basic-syntax.html 或 /python3/python3-basic-syntax.html,需要使用 urllib.parse.urljoin 统一转换为标准的绝对 URL,并进行去重处理。
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
BASE_URL = "https://www.runoob.com/python3/python3-tutorial.html"
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
def get_chapter_links():
response = requests.get(BASE_URL, headers=HEADERS, timeout=15)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
sidebar = soup.find('div', class_='left-column')
if not sidebar:
print("未找到左侧目录容器,请检查网络或页面结构")
return []
chapters = []
seen_urls = set()
for a in sidebar.find_all('a', href=True):
title = a.get_text(strip=True)
href = a['href']
# 排除外链或锚点
if href.startswith('#') or href.startswith('javascript:'):
continue
full_url = urljoin(BASE_URL, href)
if full_url not in seen_urls:
seen_urls.add(full_url)
chapters.append({
"title": title,
"url": full_url
})
print(f"成功解析到 {len(chapters)} 个章节链接")
return chapters
步骤 2:下载并净化单篇 HTML 内容
直接保存完整的原始网页会携带大量与阅读无关的代码(如外部广告脚本、页面底部统计等)。为了获得纯净的离线体验,更推荐提取正文区域 .article-intro 的 HTML 片段,并为其包裹一层极简、美观的离线 HTML 模板。
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{title}</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif;
line-height: 1.8;
max-width: 900px;
margin: 40px auto;
padding: 0 20px;
color: #333;
background-color: #FAFAFA;
}}
.content {{
background: #FFF;
padding: 30px;
border-radius: 6px;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}}
pre, code {{
background-color: #F4F4F4;
font-family: Consolas, Monaco, monospace;
border-radius: 4px;
}}
pre {{ padding: 15px; overflow-x: auto; }}
a {{ color: #0066CC; text-decoration: none; }}
.nav-back {{ margin-bottom: 20px; }}
</style>
</head>
<body>
<div class="content">
<div class="nav-back"><a href="index.html">← 返回目录首页</a></div>
{body}
</div>
</body>
</html>
"""
四、完整可运行的批量下载脚本
将上述逻辑整合为完整脚本。脚本会自动在当前工作目录下创建 runoob_python_offline 文件夹,把章节正文按编号顺序依次写入 .html 文件,并在根目录生成 index.html 目录导航页。
import os
import re
import time
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
# 1. 目标基础配置
BASE_URL = "https://www.runoob.com/python3/python3-tutorial.html"
OUTPUT_DIR = "runoob_python_offline"
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title}</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif;
line-height: 1.8;
max-width: 900px;
margin: 40px auto;
padding: 0 20px;
color: #333;
background-color: #F8F7F3;
}}
.content-box {{
background: #FFFFFF;
padding: 36px 40px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
border: 1px solid #E2DFD8;
}}
pre, code {{
background-color: #F2EFE9;
font-family: Consolas, Monaco, monospace;
border-radius: 4px;
}}
pre {{ padding: 14px 18px; overflow-x: auto; }}
a {{ color: #B96555; text-decoration: none; }}
a:hover {{ text-decoration: underline; }}
.nav-header {{
margin-bottom: 24px;
padding-bottom: 12px;
border-bottom: 1px solid #E2DFD8;
font-size: 14px;
}}
</style>
</head>
<body>
<div class="content-box">
<div class="nav-header">
<a href="index.html">← 返回离线目录首页</a>
</div>
{body}
</div>
</body>
</html>
"""
def clean_filename(filename):
"""过滤文件名中的非法字符"""
return re.sub(r'[\\/*?:"<>|]', '_', filename)
def main():
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
print("正在请求菜鸟教程 Python 栏目首页...")
session = requests.Session()
session.headers.update(HEADERS)
try:
resp = session.get(BASE_URL, timeout=15)
resp.encoding = 'utf-8'
except Exception as e:
print(f"请求首页失败: {e}")
return
soup = BeautifulSoup(resp.text, 'html.parser')
sidebar = soup.find('div', class_='left-column')
if not sidebar:
print("未定位到目录容器 .left-column,请检查网页结构。")
return
# 提取目录列表
chapter_list = []
seen_urls = set()
for a in sidebar.find_all('a', href=True):
href = a['href']
title = a.get_text(strip=True)
if href.startswith('#') or href.startswith('javascript:'):
continue
full_url = urljoin(BASE_URL, href)
if full_url not in seen_urls:
seen_urls.add(full_url)
chapter_list.append((title, full_url))
total = len(chapter_list)
print(f"共发现 {total} 个教程章节,准备开始下载...")
downloaded_records = []
# 逐篇下载与保存
for index, (title, url) in enumerate(chapter_list, start=1):
safe_title = clean_filename(title)
file_name = f"{index:02d}_{safe_title}.html"
file_path = os.path.join(OUTPUT_DIR, file_name)
print(f"[{index}/{total}] 正在抓取: {title} ...")
try:
r = session.get(url, timeout=15)
r.encoding = 'utf-8'
page_soup = BeautifulSoup(r.text, 'html.parser')
# 定位核心正文容器
article = page_soup.find('div', class_='article-intro')
if not article:
article = page_soup.find('div', class_='article')
if article:
# 移除可能存在的站内广告模块或多余样式标签
for bad_tag in article.find_all(['script', 'ins']):
bad_tag.decompose()
body_content = article.decode_contents()
else:
body_content = f"<p>未能提取到正文节点,原始链接: <a href='{url}'>{url}</a></p>"
full_html = HTML_TEMPLATE.format(title=title, body=body_content)
with open(file_path, 'w', encoding='utf-8') as f:
f.write(full_html)
downloaded_records.append((title, file_name))
# 礼貌抓取间隔,避免触发服务器频控
time.sleep(1)
except Exception as e:
print(f"下载章节 [{title}] 失败: {e}")
# 生成索引页 index.html
generate_index_page(downloaded_records)
print(f"\n全部下载完成!请打开 {os.path.join(OUTPUT_DIR, 'index.html')} 开始离线阅读。")
def generate_index_page(records):
index_path = os.path.join(OUTPUT_DIR, "index.html")
list_items = "".join([f'<li><a href="{fn}">{title}</a></li>' for title, fn in records])
index_html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>菜鸟教程 Python 离线导航目录</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif;
line-height: 1.8;
max-width: 800px;
margin: 40px auto;
padding: 0 20px;
background-color: #F8F7F3;
color: #30363C;
}}
.box {{
background: #FFF;
padding: 36px 40px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
border: 1px solid #E2DFD8;
}}
h1 {{ font-size: 24px; margin-bottom: 20px; border-bottom: 2px solid #B96555; padding-bottom: 10px; }}
ol {{ padding-left: 24px; }}
li {{ margin-bottom: 10px; }}
a {{ color: #30363C; text-decoration: none; font-size: 16px; }}
a:hover {{ color: #B96555; text-decoration: underline; }}
</style>
</head>
<body>
<div class="box">
<h1>菜鸟教程 Python 离线知识库导航</h1>
<ol>{list_items}</ol>
</div>
</body>
</html>
"""
with open(index_path, 'w', encoding='utf-8') as f:
f.write(index_html)
if __name__ == '__main__':
main()
五、操作细节与注意事项
关键提醒:
- 显式强制 UTF-8 编码:
requests自动根据 HTTP Header 推测的编码有时会误判为 ISO-8859-1,必须在读取前显式赋值response.encoding = 'utf-8',否则保存到本地的文件可能出现中文乱码。 - 请求频率与礼貌抓取:每次请求之间加入
time.sleep(1)。教程总篇数通常在一两百篇左右,平缓抓取几分钟即可完成,切忌开启高并发无延迟轰炸,以免触发服务端的防刷或 IP 封禁。 - 文件命名清洗:章节标题中可能包含问号、冒号、斜杠等在 Windows 或 macOS 文件系统中受限的字符,必须先经过过滤替换后再作为本地文件名保存。
- 图片等外部静态资源:教程中的示意图若使用网络绝对路径(如
https://www.runoob.com/wp-content/...),本地打开 HTML 在联网状态下可正常展示。若需彻底断网离线浏览,可在遍历时查找<img src="...">标签将图片一并下载到本地images/文件夹,并把src改写为相对路径。
六、验证结果
运行脚本后,检查 runoob_python_offline 目录:双击打开其中的 index.html,应当能看到所有按序号排列的 Python 章节列表;任意点击一章节链接,即可流畅打开排版纯净、代码块高亮正常、且带有返回目录功能的本地 HTML 教程。此时整个 Python 栏目已成功转为本地持久化文档,即使处于离线或弱网环境中,也能随时无障碍查阅与学习。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













