Python爬取小说
时间: 2025-08-18 17:23:21 浏览: 14
<think>为了爬取小说,我们需要选择一个小说网站,并分析其页面结构。这里以“笔趣阁”为例(注意:请确保遵守网站的使用条款,爬虫仅用于学习目的,且不要对网站造成过大压力)。
步骤:
1. 确定要爬取的小说目录页URL。
2. 获取目录页的HTML,解析出所有章节的链接。
3. 遍历每个章节链接,获取章节内容。
4. 将章节内容保存到本地文件中。
我们将使用requests获取网页,使用BeautifulSoup解析HTML。
注意:有些网站有反爬机制,可能需要设置请求头(User-Agent)等。
示例:爬取《斗破苍穹》在笔趣阁中的小说。
假设目录页URL:`http://www.biquge.com.tw/0_1/`
由于网站可能变化,以下代码仅作为示例,实际使用时需要根据目标网站结构调整。
我们将:
- 定义函数获取网页内容。
- 解析目录页,得到章节链接列表。
- 遍历每个章节,获取章节标题和正文。
- 将每个章节写入一个文本文件。
注意:为了避免请求过快被屏蔽,我们在每个请求之间加入短暂的延迟。
代码实现:</think>### Python爬取小说解决方案
我将使用`requests`获取网页内容,`BeautifulSoup`解析HTML,并添加反爬虫措施(随机User-Agent和延迟)。以下是完整代码:
```python
import requests
from bs4 import BeautifulSoup
import time
import random
import re
from fake_useragent import UserAgent
def get_novel_content(novel_url):
"""爬取小说内容并保存到本地"""
# 设置随机User-Agent
ua = UserAgent()
headers = {'User-Agent': ua.random}
try:
# 获取目录页
response = requests.get(novel_url, headers=headers, timeout=10)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
# 解析小说标题
novel_title = soup.find('h1').text.strip()
print(f"开始爬取: 《{novel_title}》")
# 解析章节链接
chapter_links = []
for link in soup.select('.listmain a'):
if 'href' in link.attrs and '章' in link.text:
chapter_links.append({
'title': link.text.strip(),
'url': requests.compat.urljoin(novel_url, link['href'])
})
# 创建保存文件
filename = f"{novel_title}.txt"
with open(filename, 'w', encoding='utf-8') as f:
f.write(f"《{novel_title}》\n\n")
# 遍历所有章节
for i, chapter in enumerate(chapter_links):
try:
# 随机延迟防止被封(1-3秒)
time.sleep(random.uniform(1, 3))
# 获取章节内容
chap_res = requests.get(
chapter['url'],
headers={'User-Agent': ua.random},
timeout=10
)
chap_res.encoding = 'utf-8'
chap_soup = BeautifulSoup(chap_res.text, 'html.parser')
# 提取正文内容 (根据网站结构调整选择器)
content_div = chap_soup.select_one('#chaptercontent, .content, .novelcontent')
if not content_div:
print(f"警告: 未找到 {chapter['title']} 的正文")
continue
# 清理无用标签和广告
for tag in content_div.select('script, .adsbygoogle'):
tag.decompose()
# 处理文本格式
content = content_div.text.strip()
content = re.sub(r'\s+', '\n', content) # 合并多余空白
content = re.sub(r'[\u3000]+', ' ', content) # 替换全角空格
# 写入文件
f.write(f"第{i+1}章 {chapter['title']}\n\n")
f.write(content + "\n\n")
f.flush() # 实时写入
print(f"已完成: {chapter['title']} ({i+1}/{len(chapter_links)})")
except Exception as e:
print(f"章节 {chapter['title']} 获取失败: {str(e)}")
print(f"\n爬取完成! 文件已保存为: {filename}")
return filename
except Exception as e:
print(f"爬取失败: {str(e)}")
return None
if __name__ == "__main__":
# 示例URL (替换为目标小说目录页)
novel_url = "https://www.biqg.cc/book/1/"
get_novel_content(novel_url)
```
### 代码详解
1. **反爬虫措施**:
- `UserAgent().random`:每次请求使用随机User-Agent
- `time.sleep(random.uniform(1, 3))`:章节间随机延迟
- `timeout=10`:设置请求超时
2. **核心功能**:
- 目录页解析:通过CSS选择器`.listmain a`获取章节链接
- 内容清洗:删除广告标签(`script, .adsbygoogle`),正则表达式清理空白字符
- 编码处理:强制使用UTF-8编码防止乱码
3. **文件处理**:
- 实时写入并`flush()`:防止意外中断丢失数据
- 章节标题编号:自动添加章节序号
4. **错误处理**:
- 章节级异常捕获:单章失败不影响整体流程
- URL拼接:`urljoin`处理相对路径链接
### 使用说明
1. 安装依赖:
```bash
pip install requests beautifulsoup4 fake-useragent
```
2. 修改目标URL:
```python
novel_url = "https://www.example.com/novel/" # 替换为实际小说目录页
```
3. 常见网站适配调整:
- **正文选择器**:修改`#chaptercontent`为目标网站的正文容器选择器
- **章节过滤**:修改`'章' in link.text`为实际章节标识
> ⚠️ 注意:请遵守目标网站的`robots.txt`规定,仅用于个人学习,避免高频访问造成服务器压力。
阅读全文
相关推荐










