怎么用python爬多个小说章节
时间: 2023-05-16 21:06:10 浏览: 116
您可以使用Python中的requests和BeautifulSoup库来爬取多个小说章节。首先,您需要找到小说的网站,并确定每个章节的URL格式。然后,您可以使用requests库发送HTTP请求,并使用BeautifulSoup库解析HTML响应。最后,您可以将每个章节的文本保存到本地文件中。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 小说网站的URL和章节URL格式
novel_url = 'https://www.example.com/novel'
chapter_url_format = 'https://www.example.com/novel/chapter-{}.html'
# 爬取的章节数
start_chapter = 1
end_chapter = 10
# 循环爬取每个章节
for chapter in range(start_chapter, end_chapter+1):
# 构造章节URL
chapter_url = chapter_url_format.format(chapter)
# 发送HTTP请求并解析HTML响应
response = requests.get(chapter_url)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取章节文本并保存到本地文件
chapter_text = soup.find('div', {'class': 'chapter-text'}).text
with open(f'chapter{chapter}.txt', 'w', encoding='utf-8') as f:
f.write(chapter_text)
```
请注意,此示例代码仅供参考,实际情况可能因小说网站的不同而有所不同。