小白教程:Python 怎么写一个抓取小说的自动化脚本
用 Python 编写一个自动化抓取小说的脚本,就能轻松解决这个问题。本文将以小白视角,从零开始教你编写一个简单的小说抓取脚本,无需复杂的编程基础,只需跟随步骤操作,就能让计算机自动帮你下载整本小说。
一、准备工作:认识核心工具
在开始编写脚本前,我们需要先了解并安装两个核心工具,它们是实现小说抓取的关键:
1. Python 解释器
Python 是一门简单易学的编程语言,我们的脚本需要通过它来运行。
- 下载地址:https://www.python.org/downloads/(选择最新的 3.x 版本,如 3.12.0)
- 安装注意:Windows 系统安装时务必勾选 “Add Python to PATH cqe.czbosen.com”,这样才能在命令行中直接使用 Python 命令。安装完成后,打开 “命令提示符”(Win+R 输入 cmd),输入python --version,若显示版本号则说明安装成功。
2. 第三方库
我们需要两个专门处理网络请求和网页解析的库:
- requests:用于向小说网站发送网络请求,获取网页内容。
- BeautifulSoup:用于解析网页 HTML 代码,提取小说章节标题和内容。
安装方法:打开命令提示符,输入以下两条命令(分别安装两个库):
pip install requests
pip install beautifulsoup4
安装完成后,输入pip list,cqd.dnzpack.com若能看到requests和beautifulsoup4则说明安装成功。
二、脚本原理:抓取小说的基本逻辑
简单来说,抓取小说的过程就像模拟人浏览网页并复制内容,主要分为三个步骤:
- 获取章节列表:访问小说目录页,提取所有章节的标题和对应的链接。
- 下载章节内容:逐个访问章节链接,提取正文内容。
- 保存到本地:将提取的标题和内容按顺序写入 TXT 文件,形成完整的小说。
以 “笔趣阁”(示例网站,实际使用需遵守网站规则)的某本小说为例,我们来实现这个过程。
三、编写脚本:分步骤实现
步骤 1:确定目标小说的 URL
首先需要找到你想抓取的小说的目录页 URL。例如,某本小说的目录页地址为:https://www.biquge.com/book/12345/(仅为示例,实际地址需自行查找)。
注意:选择小说网站时,优先选择结构简单、无复杂反爬机制的站点(如部分静态页面的小说站),避免选择需要登录或有验证码的网站,否则会增加脚本难度。
步骤 2:编写代码框架
新建一个文本文件,命名为novel_crawler.py(后缀必须为.py),用记事本或 VS Code 打开,先写下基本框架:
# 导入需要的库
import requests
from bs4 import BeautifulSoup
import time
# 小说目录页URL(替换为你要抓取的小说目录页)
catalog_url = "https://www.biquge.com/book/12345/"
# 保存小说的文件夹(可自定义路径)
save_path = "D:/novels/"
步骤 3:获取章节列表
目录页中包含了小说所有章节的链接和标题,我们需要用requests获取页面内容,再用BeautifulSoup cqc.jieyanbaba.com提取这些信息:
def get_chapter_list(catalog_url):
# 发送请求获取目录页内容
# 添加请求头,模拟浏览器访问(避免被网站识别为爬虫)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(catalog_url, headers=headers)
# 设置编码,避免中文乱码
response.encoding = "utf-8"
# 解析网页内容
soup = BeautifulSoup(response.text, "html.parser")
# 查找章节列表(需根据实际网页结构调整选择器)
# 打开目录页,按F12查看章节链接的HTML标签,例如<a>标签的class为"chapter"
chapter_tags = soup.find_all("a", class_="chapter")
# 提取章节标题和链接
chapter_list = []
for tag in chapter_tags:
title = tag.text # 章节标题
url = tag["href"] cqb.mabohu.com 章节链接
# 处理相对链接(如果链接是相对路径,需要拼接成完整URL)
if not url.startswith("http"):
url = catalog_url + url
chapter_list.append({"title": title, "url": url})
return chapter_list
关键说明:
- headers的作用是模拟浏览器访问,部分网站会拒绝没有请求头的访问。
- soup.find_all()中的参数需要根据实际网页调整:打开目录页→按 F12→用 “开发者工具” 的选择工具点击章节链接,查看其 HTML 标签(如<a class="chapter" href="xxx">第一章</a>),则class_应为"chapter"。
步骤 4:下载章节内容
获取章节链接后,需要逐个访问并提取正文内容:
def get_chapter_content(chapter_url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(chapter_url, headers=headers)
response.encoding = "utf-8"
soup = BeautifulSoup(response.text, "html.parser")
# 提取章节标题(部分网站章节页标题可能与目录页不同)
title_tag = soup.find("h1") # 假设标题在<h1>标签中
title = title_tag.text if title_tag else "未知章节"
# 提取正文内容(根据实际网页结构调整选择器)
# 通常正文在<div class="content">cqa.sichuanaoshu.com或<div id="content">中
content_tag = soup.find("div", class_="content")
if not content_tag:
return title, "无法获取内容"
# 提取所有段落,去除多余的空行和广告
paragraphs = content_tag.find_all("p")
content = "\n\n".join([p.text.strip() for p in paragraphs if p.text.strip()])
# 去除内容中的广告文字(如“cq.hkaberry.com请记住本站网址”)
content = content.replace("请记住本站网址:www.biquge.com", "")
content = content.replace("章节错误,点此报送", "")
return title, content
关键说明:
- 正文提取的class_参数需要根据实际网页调整(方法同上,用 F12 查看正文区域的 HTML 标签)。
- 很多小说网站会在正文中插入广告文字,可用replace()方法去除。
步骤 5:保存小说到本地
将所有章节内容按顺序写入 TXT 文件,并创建保存目录(如果目录不存在):
import os
def save_novel(chapter_list, save_path):
# 创建保存目录
if not os.path.exists(save_path):
os.makedirs(save_path)
# 小说文件名(以目录页标题命名)
novel_title = "我的小说" #cpv.dytalent.com 可根据实际情况从目录页提取
file_path = os.path.join(save_path, f"{novel_title}.txt")
# 打开文件,逐章写入
with open(file_path, "w", encoding="utf-8") as f:
total = len(chapter_list)
for i, chapter in enumerate(chapter_list):
try:
# 打印进度
print(f"正在下载第{i+1}/{total}章:{chapter['title']}")
# 获取章节内容
title, content = get_chapter_content(chapter["url"])
# 写入文件
f.write(f"【{title}】\n\n")
f.write(content + "\n\n")
# 每下载一章休息1秒,避免请求过于频繁被封IP
time.sleep(1)
except Exception as e:
print(f"下载失败:{chapter['title']},错误:{str(e)}")
# 记录失败的章节,方便后续处理
with open("failed_chapters.txt", "a", encoding="utf-8") as err_f:
err_f.write(f"{chapter['title']}: {chapter['url']}\n")
print(f"小说下载完成,保存路径:cpu.sdhxyn.com{file_path}")
步骤 6:组合所有功能
在脚本最后添加主函数,调用前面定义的功能:
def main():
# 获取章节列表
print("正在获取章节列表...")
chapter_list = get_chapter_list(catalog_url)
if not chapter_list:
print("无法获取章节列表,请检查URL或网站结构")
return
print(f"共发现{len(chapter_list)}个章节")
# 下载并保存小说
save_novel(chapter_list, save_path)
# 运行主函数
if __name__ == "__main__":
main()
四、完整代码与使用说明
完整代码
将以上代码整合,最终的novel_crawler.py如下(需根据实际网站调整选择器):
import requests
from bs4 import BeautifulSoup
import time
import os
# 小说目录页URL(替换为目标小说的目录页)
catalog_url = "http://cpt.syhcombat.com /book/12345/"
# 保存路径
save_path = "D:/novels/"
def get_chapter_list(catalog_url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(catalog_url, headers=headers)
response.encoding = "utf-8"
soup = BeautifulSoup(response.text, "html.parser")
# 请根据实际网页调整章节标签的选择器
chapter_tags = soup.find_all("a", class_="chapter")
chapter_list = []
for tag in chapter_tags:
title = tag.text
url = tag["href=cps.qianbaihua.cn"]
if not url.startswith("http"):
url = catalog_url + url
chapter_list.append({"title": title, "url": url})
return chapter_list
def get_chapter_content(chapter_url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(chapter_url, headers=headers)
response.encoding = "utf-8"
soup = BeautifulSoup(response.text, "html.parser")
title_tag = soup.find("h1")
title = title_tag.text if title_tag else "未知章节"
# 请根据实际网页调整正文标签的选择器
content_tag = soup.find("div", class_="content")
if not content_tag:
return title, "无法获取内容"
paragraphs = content_tag.find_all("p")
content = "\n\n".join([p.text.strip() for p in paragraphs if p.text.strip()])
# 去除广告(根据实际情况修改)
content = content.replace("请记住本站网址", "cpr.sinoebuy.com.cn").replace("章节错误", "")
return title, content
def save_novel(chapter_list, save_path):
if not os.path.exists(save_path):
os.makedirs(save_path)
novel_title = "我的小说"
file_path = os.path.join(save_path, f"{novel_title}.txt")
with open(file_path, "w", encoding="utf-8") as f:
total = len(chapter_list)
for i, chapter in enumerate(chapter_list):
try:
print(f"正在下载第{i+1}/{total}章:{chapter['title']}")
title, content = get_chapter_content(chapter["url"])
f.write(f"【{title}】\n\n{content}\n\n")
time.sleep(1)
except Exception as e:
print(f"cpq.vl588.cn下载失败:{chapter['title']},错误:{str(e)}")
with open("failed_chapters.txt", "a", encoding="utf-8") as err_f:
err_f.write(f"{chapter['title']}: {chapter['url']}\n")
print(f"下载完成,路径:{file_path}")
def main():
print("正在获取章节列表...")
chapter_list = get_chapter_list(catalog_url)
if not chapter_list:
print("获取章节失败")
return
print(f"共{len(chapter_list)}章")
save_novel(chapter_list, save_path)
if __name__ == "__main__":
main()
使用方法
- 修改 URL 和选择器:
-
- 将catalog_url替换为你要抓取的小说目录页 URL。
-
- 打开目录页→按 F12→用选择工具查看章节链接的 HTML 标签,修改get_chapter_list中的find_all("a", class_="chapter"cpp.fzxjrz.com)(例如如果章节链接的 class 是"list-chapter",则改为class_="list-chapter")。
-
- 同理,查看章节页正文的 HTML 标签,修改get_chapter_content中的find("div", class_="content")。
- 运行脚本:
-
- 在脚本所在文件夹按住 Shift + 右键,选择 “在此处打开 PowerShell 窗口”。
-
- 输入python novel_crawler.py,回车运行,脚本会自动开始下载。
五、常见问题与解决方法
1. 中文乱码
现象:保存的 TXT 文件中中文显示为乱码。
解决:确保open()函数中指定了encoding="utf-8",如with open(file_path, "w", encoding="utf-8") as f。
2. 无法获取章节列表或内容
现象:提示 “无法获取章节列表” 或内容为空。
解决:
- 检查catalog_url是否正确,能否在浏览器中打开。
- 用 F12 检查网页结构,确认find_all cpo.imeilaoban.com的参数是否与实际标签匹配(class 名称是否正确,是否有拼写错误)。
- 部分网站会用 JavaScript 动态加载章节,这种情况需要使用selenium库(较复杂,新手可换一个静态页面的网站)。
3. 被网站封禁 IP
现象:一开始能下载,后来突然失败。
解决:
- 增加time.sleep()的时间(如改为 2 秒),降低请求频率。
- 更换网络(如用手机热点),获取新的 IP 地址。
- 添加代理 IP(进阶操作,可参考相关教程)。
4. 章节顺序错乱
现象:下载的章节顺序与目录页不一致。
解决:部分网站的章节链接在 HTML 中是按顺序排列的,但若存在 “最新章节” 在前的情况,可在chapter_list提取后手动排序(如根据章节号排序)。
六、法律与道德注意事项
- 遵守网站规则:查看小说网站的robots.txt(如https://www.biquge.com/robots.txt),了解是否允许爬虫抓取。部分网站明确禁止抓取,需尊重其规定。
- 非商业用途:抓取的小说仅可用于个人离线阅读,不得用于商业传播或盈利,避免侵犯版权。
- 适度抓取:不要频繁请求同一网站,以免影响网站服务器正常运行,做一个 “友好的爬虫”。
七、进阶学习建议
如果想让脚本更强大,可以尝试学习以下功能:
- 用selenium处理动态加载的网站(如需要点击 “下一章” 的网站)。
- 实现断点续传,支持暂停后继续下载。
- 自动识别小说封面,生成带封面的电子书(如 EPUB 格式)。
通过这个简单的脚本,你不仅能轻松获取小说,还能入门 Python 爬虫的基本原理。动手尝试吧,遇到问题时多查看报错信息,逐步调整代码,你会发现编程其实没那么难!
如果在实践中遇到特殊问题,欢迎在评论区留言,我们一起探讨解决方法~
更多推荐



所有评论(0)