使用 Python 爬虫下载网络小说去除广告干扰
前言
在闲暇时间阅读网络小说是一种常见的消遣方式,但在浏览网页版小说时,经常会被弹窗广告、侧边栏广告以及误触跳转等干扰体验。尤其是想要点击下一章时,不小心点击到广告链接会严重影响阅读流畅度。为了解决这一问题,我们可以利用 Python 编写一个简单的网络爬虫程序,将目标小说的章节内容抓取并保存为本地文本文件,从而实现无广告的离线阅读。

一、环境配置
在开始编写代码之前,需要确保开发环境满足以下要求:
- Python 版本:推荐使用 Python 3.7 及以上版本(本文基于 3.7.3 编写)。
- 集成开发环境 (IDE):建议使用 PyCharm 或 VS Code,便于代码调试与管理。
- 依赖库安装:
requests:用于发送 HTTP 请求。lxml:用于解析 HTML 文档,支持 XPath 查询。time:内置模块,用于控制请求频率,防止触发反爬机制。
安装命令如下:
pip install requests lxml
二、准备工作
- 创建项目目录:在电脑指定位置创建一个文件夹,用于存放爬取的小说文件和脚本代码。
- 确定目标网站:选择一个允许爬取的小说网站,获取其书籍详情页和章节页的 URL 结构。
- 分析页面结构:使用浏览器开发者工具(F12)查看 HTML 源码,定位小说名称、目录列表及正文内容的 DOM 节点路径(XPath)。无需额外安装插件,现代浏览器已内置强大的元素检查功能。
三、核心代码实现
以下是完整的爬虫脚本示例,包含异常处理与基础的反爬策略:
import requests
from lxml import etree
import time
import os
# 设置目标书籍的详情页 URL
target_url = 'https://www.biquge365.net/newbook/33411/'
# 设置请求头,模拟浏览器访问
headers = {
'Referer': 'https://www.biquge365.net/book/33411/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.39'
}
def fetch_novel_info(url):
:
response = requests.get(url, headers=headers, verify=)
response.encoding = response.apparent_encoding
html = etree.HTML(response.text)
novel_name_list = html.xpath()
novel_name_list:
()
, []
novel_name = novel_name_list[].strip()
chapter_links = html.xpath()
novel_name, chapter_links
Exception e:
()
, []
():
:
response = requests.get(chapter_url, headers=headers)
response.encoding = response.apparent_encoding
html = etree.HTML(response.text)
title_list = html.xpath()
title_list:
,
chapter_title = title_list[]
content_list = html.xpath()
content = .join(content_list)
chapter_title, content
Exception e:
()
,
():
novel_name, chapters = fetch_novel_info(target_url)
novel_name chapters:
()
save_dir =
os.path.exists(save_dir):
os.makedirs(save_dir)
()
link chapters:
full_url = + link
title, content = download_chapter(full_url, headers)
title content:
file_path = os.path.join(save_dir, )
(file_path, , encoding=) f:
f.write(title + + content)
()
time.sleep()
__name__ == :
main()


