用Python写一个小说下载脚本
时间: 2023-05-14 10:05:55 浏览: 97
好的,我可以为您提供一个Python小说下载脚本的示例代码:
```python
import requests
from bs4 import BeautifulSoup
def download_novel(url):
# 获取小说目录页的HTML代码
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取小说标题
title = soup.find('h1').text.strip()
# 创建一个空的字符串,用于存储小说内容
novel_content = ''
# 获取小说每一章的链接,并逐一下载
chapter_list = soup.find_all('a', class_='chapter')
for chapter in chapter_list:
chapter_url = chapter['href']
chapter_title = chapter.text.strip()
# 获取章节内容页的HTML代码
response = requests.get(chapter_url)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取章节内容
chapter_content = soup.find('div', class_='read-content').text.strip()
# 将章节标题和内容添加到小说内容中
novel_content += chapter_title + '\n\n' + chapter_content + '\n\n'
# 将小说内容保存到文件中
with open(title + '.txt', 'w', encoding='utf-8') as f:
f.write(novel_content)
print('小说下载完成!')
if __name__ == '__main__':
url = 'https://www.xxxx.com/novel/123456/'
download_novel(url)
```
请注意,这只是一个示例代码,您需要根据实际情况进行修改和调整。另外,小说下载涉及版权问题,请您在下载前确认小说的版权情况,以免侵犯他人权益。