python爬虫爬取小说
时间: 2025-05-10 18:25:26 浏览: 32
### 如何用Python爬虫抓取网络小说内容
#### 使用的库
为了完成这一任务,通常会使用 `requests` 库来发送 HTTP 请求获取网页内容,使用 `parsel` 或 `BeautifulSoup` 来解析 HTML 文档提取所需的数据[^1]。此外,还可以引入 `tqdm` 库用于显示进度条,使程序运行过程更加直观。
#### 抓取流程概述
在实际操作中,需要先分析目标网站的小说页面结构,找到存储章节链接和正文的具体标签及其属性[^3]。通过这些信息构建请求 URL 并逐步访问各个章节页面,最终将所有章节的内容按顺序保存到本地文件中。
以下是基于上述方法的一个基本实现框架:
```python
import os
import requests
from parsel import Selector
from tqdm import tqdm
def fetch_chapter(url):
response = requests.get(url)
selector = Selector(response.text)
title = selector.css('h1::text').get() # 假设标题位于<h1>标签内
content = '\n'.join(selector.css('.content p::text').extract()) # 假设正文段落在.content类下的<p>标签里
return title, content
def save_novel(chapters, filename="novel.txt"):
with open(filename, 'w', encoding='utf-8') as f:
for chapter in chapters:
f.write(f"{chapter['title']}\n\n{chapter['content']}\n{'-'*40}\n")
if __name__ == "__main__":
base_url = input("请输入小说目录页URL:")
resp = requests.get(base_url)
sel = Selector(resp.text)
links = ["http://example.com/" + link for link in sel.css(".list a::attr(href)").extract()] # 构造各章节点击路径列表
results = []
for url in tqdm(links[:5]): # 测试前五章
try:
t,c = fetch_chapter(url)
results.append({"title":t,"content":c})
except Exception as e:
print(e)
save_novel(results)
```
此代码片段展示了如何定义函数分别处理单个章节下载以及整个书籍存盘的工作;并通过循环调用来遍历多个章节地址进行批量采集。
需要注意的是,在开发此类应用时应遵循robots协议尊重原站点规定,并注意适当设置延时避免高频次请求给服务器带来压力[^2]。
阅读全文
相关推荐












