Python爬虫在网络小说方面有着广泛的应用,许多小说爱好者将Python作为获取小说的神器。Python爬虫可以帮助我们快速地获得网络小说的内容,方便我们阅读,分享。下面我们将学习如何使用Python爬虫来爬取网络小说,以经典的《红楼梦》为例。
# 导入所需要的库
import requests
from bs4 import BeautifulSoup
# 请求URL
url = 'https://book.qidian.com/info/1004608738'
# 使用requests发送HTTP请求
response = requests.get(url)
# 设置编码方式,避免乱码
response.encoding = 'utf-8'
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取小说名称、作者、简介等信息
book_name = soup.find('h1', {'class': 'book-title'}).text
author_name = soup.find('a', {'class': 'writer'}).text
summary = soup.find('div', {'class': 'intro'}).text.strip()
# 输出小说信息
print('小说名称:', book_name)
print('作者:', author_name)
print('简介:', summary)
# 获取小说章节列表
chapter_list = soup.find_all('li', {'data-rid': True})
# 遍历所有章节
for chapter in chapter_list:
# 获取章节名称和URL
chapter_name = chapter.find('a').text
chapter_url = 'https:' + chapter.find('a')['href']
# 获取章节内容并保存至本地文本文件
response = requests.get(chapter_url)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.find('div', {'class': 'read-content j_readContent'}).text
with open(book_name + '.txt', 'a', encoding='utf-8') as f:
f.write(chapter_name + '\n\n')
f.write(content + '\n\n')

通过以上代码,我们可以获取到《红楼梦》的小说信息以及章节内容,并将章节内容保存至本地文本文件。这为我们阅读小说提供了极大的便利。