小说爬虫工具:一键获取热门小说
这款小说爬虫工具能够快速搜索并获取热门小说,支持两种小说源选择,方便用户获取小说内容。
使用方法:
- 运行脚本
- 选择小说源 (1 或 2):
- 1 - 使用预设小说源 (示例:https://www.biquge66.net/book/4772/)
- 2 - 搜索小说,脚本将从搜索结果中获取小说链接
- 输入小说名称
- 脚本将自动获取小说所有章节内容并打印
功能:
- 支持两种小说源选择
- 自动获取小说所有章节内容
- 支持多页章节内容拼接
- 移除页面无关信息
- 打印章节标题和内容
示例代码:
import requests
from bs4 import BeautifulSoup
def crawl_novel(url):
# 发送 HTTP GET 请求获取小说主页面
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析小说主页面内容
soup = BeautifulSoup(response.content, 'html.parser')
# 找到所有章节链接
chapter_lists = soup.find_all('div', class_='flex flex-between book-info-main')
# 循环遍历每个章节链接并提取章节内容
for chapter_list in chapter_lists:
for chapter in chapter_list.find_all('a', rel='chapter'):
chapter_title = chapter.text # 获取章节标题
chapter_url = 'https://www.biquge66.net' + chapter['href'] # 构建完整的章节 URL
# 发送 HTTP GET 请求获取章节内容的第一页
chapter_response = requests.get(chapter_url)
chapter_soup = BeautifulSoup(chapter_response.content, 'html.parser')
# 找到章节内容的第一页
chapter_content = chapter_soup.find('div', id='booktxt')
# 提取并打印章节内容的第一页
if chapter_content:
chapter_text = chapter_content.text.replace('本站最新网址:www.biquge66.net', '') # 移除网站信息
# 检查是否有第二页
chapter_url2 = chapter_url.replace('.html', '_2.html')
chapter_response2 = requests.get(chapter_url2)
chapter_soup2 = BeautifulSoup(chapter_response2.content, 'html.parser')
chapter_content2 = chapter_soup2.find('div', id='booktxt')
# 如果有第二页,将它与第一页拼接
if chapter_content2:
chapter_text2 = chapter_content2.text.replace('本站最新网址:www.biquge66.net', '') # 移除网站信息
chapter_text += chapter_text2
print(f'{chapter_title}:
{chapter_text}
')
else:
print(f'无法获取章节内容: {chapter_title}
')
else:
print(f'无法获取小说页面: {url}')
def search_novel():
novel_name = input('输入小说名称: ')
# 构建搜索 URL
search_url = f'https://www.biquge66.net/search/?searchkey={novel_name}'
# 发送 HTTP GET 请求获取搜索页面
search_response = requests.get(search_url)
# 检查请求是否成功
if search_response.status_code == 200:
# 解析搜索页面内容
search_soup = BeautifulSoup(search_response.content, 'html.parser')
# 找到第一个搜索结果并提取其 href
first_result = search_soup.find('div', class_='image').find('a')
if first_result:
novel_href = first_result['href']
# 构建小说主页面 URL
novel_url = f'https://www.biquge66.net{novel_href}'
crawl_novel(novel_url)
else:
print('未找到小说搜索结果。')
else:
print(f'无法获取搜索结果页面: {search_url}')
# 提示用户选择小说源
novel_source = input('选择小说源 (1 或 2): ')
if novel_source == '1':
crawl_novel('https://www.biquge66.net/book/4772/')
elif novel_source == '2':
search_novel()
else:
print('无效的小说源选择。请重新尝试。')
注意:
- 代码中使用了 requests 和 BeautifulSoup 库,需要先安装。
- 为了避免被网站封锁,建议使用代理服务器。
- 本脚本仅供学习和研究使用,请勿用于商业目的。
原文地址: https://www.cveoy.top/t/topic/qB8I 著作权归作者所有。请勿转载和采集!