爬取一本小说的python爬虫代码

爬取一本小说的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)

运行结果
在这里插入图片描述

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客李华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值