爬取一本小说的python爬虫代码
简介:本文分享一个python爬取网站小说代码演示。
- 作者简介:一名后端开发人员,每天分享后端开发以及人工智能相关技术,行业前沿信息,面试宝典。
- 座右铭:未来是不可确定的,慢慢来是最快的。
- 个人主页:极客李华-CSDN博客
- 合作方式:私聊+
- 这个专栏内容:BAT等大厂常见后端java开发面试题详细讲解,更新数目100道常见大厂java后端开发面试题。
- 我的CSDN社区:https://bbs.csdn.net/forums/99eb3042821a4432868bb5bfc4d513a8
- 微信公众号,抖音,b站等平台统一叫做:极客李华,加入微信公众号领取各种编程资料,加入抖音,b站学习面试技巧
获取小说章节
完整代码
import requests
from bs4 import BeautifulSoup
# 目标网页URL
url = 'https://www.yekan361.com/shenyinwangzuo/'
# 发送HTTP请求
response = requests.get(url)
response.raise_for_status() # 如果请求失败,将抛出异常
response.encoding = 'utf-8'
# 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到包含章节列表的<div>元素
chapter_div = soup.find('div', id='play_0')
# 检查是否找到了<div>元素
if not chapter_div:
print("没有找到章节列表的容器,请检查网页结构和提供的ID是否正确。")
else:
# 在<div>内部找到<ul>元素
chapter_list = chapter_div.find('ul')
# 检查是否找到了<ul>元素
if not chapter_list:
print("在章节列表的容器内部没有找到<ul>元素,请检查网页结构。")
else:
# 遍历每个章节的<li>元素,打印章节名称
for chapter_tag in chapter_list.find_all('li'):
# 获取<a>标签中的文本作为章节标题
chapter_title = chapter_tag.find('a').get_text(strip=True)
print(chapter_title)
效果展示
获取某一章节
完整代码
import requests
from bs4 import BeautifulSoup
# 定义一个函数来获取章节内容
def fetch_chapter_content(chapter_url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(chapter_url, headers=headers)
response.raise_for_status() # 如果请求失败,将抛出异常
response.encoding = 'utf-8' # 确保编码正确
soup = BeautifulSoup(response.text, 'html.parser')
# 查找所有的<p>标签并提取文本内容
paragraphs = soup.find_all('p')
chapter_content = '\n'.join([p.get_text(strip=True) for p in paragraphs if p.get_text(strip=True) != ''])
return chapter_content
# 测试函数
chapter_url = 'https://www.yedu360.com/shenyinwangzuo/277261.html' # 您提供的章节网页链接
chapter_content = fetch_chapter_content(chapter_url)
print(chapter_content) # 打印章节内容
效果展示
获取所有的章节的小说并且保存到txt文本里面
完整代码
import requests
import os
from bs4 import BeautifulSoup
def save_to_txt(file_name, content):
# 确保文件的目录存在,如果不存在则创建
directory = os.path.dirname(file_name)
if not os.path.exists(directory):
os.makedirs(directory, exist_ok=True) # exist_ok=True 避免在目录已存在时抛出异常
# 打开文件,如果文件不存在则创建,并追加内容
with open(file_name, 'a', encoding='utf-8') as file:
file.write(content + '\n')
# 定义一个函数来获取章节内容
def fetch_chapter_content(chapter_url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(chapter_url, headers=headers)
response.raise_for_status() # 如果请求失败,将抛出异常
response.encoding = 'utf-8' # 确保编码正确
soup = BeautifulSoup(response.text, 'html.parser')
# 查找所有的<p>标签并提取文本内容
paragraphs = soup.find_all('p')
chapter_content = '\n'.join([p.get_text(strip=True) for p in paragraphs if p.get_text(strip=True) != ''])
return chapter_content
# 目标网页URL
base_url = 'https://www.yekan361.com/feihuwaizhuan/'
# 发送HTTP请求获取章节列表
response = requests.get(base_url)
response.raise_for_status() # 如果请求失败,将抛出异常
response.encoding = 'utf-8'
# 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到包含章节列表的<div>元素
chapter_div = soup.find('div', id='play_0')
# 检查是否找到了<div>元素
if not chapter_div:
print("没有找到章节列表的容器,请检查网页结构和提供的ID是否正确。")
else:
# 在<div>内部找到<ul>元素
chapter_list = chapter_div.find('ul')
# 检查是否找到了<ul>元素
if not chapter_list:
print("在章节列表的容器内部没有找到<ul>元素,请检查网页结构。")
else:
# 存储章节内容到txt文件
txt_file_path = r'D:\系统默认\桌面\chapter_contents.txt'
# 遍历每个章节的<li>元素,打印章节名称和链接
for chapter_tag in chapter_list.find_all('li'):
# 获取<a>标签中的文本作为章节标题
chapter_title = chapter_tag.find('a').get_text(strip=True)
# 获取章节链接的相对路径
relative_link = chapter_tag.find('a')['href']
# 构造完整的章节链接
chapter_link = base_url[0:25] + relative_link
# # 打印章节标题和链接
# print(f'章节标题: {chapter_title}')
# print(f'章节链接: {chapter_link}\n')
# # 获取并打印章节内容
# chapter_content = fetch_chapter_content(chapter_link)
# print(chapter_content + '\n') # 打印章节内容
# print(chapter_content + '\n') # 打印章节内容
chapter_content = fetch_chapter_content(chapter_link)
if chapter_content:
content_to_save = f'章节标题: {chapter_title}\n章节链接: {chapter_link}\n\n{chapter_content}\n\n'
print(content_to_save)
save_to_txt(txt_file_path, content_to_save)
运行结果