python爬取小说

本文介绍了如何使用Python爬取网络小说并保存为TXT格式。通过导入fake_useragent、BeautifulSoup等库,实现网页内容的抓取、标签处理及内容写入文件。程序首先获取小说基本信息,然后遍历所有章节,逐章下载并存储。
部署运行你感兴趣的模型镜像

python爬取小说

在网上看小说,会受到网络的影响,时不时会加载不出来。因此为了看得更舒服,本文使用python将网页上的小说爬取下来并且保存为txt。

一、需要的导入的库

from fake_useragent import UserAgent
from bs4 import BeautifulSoup
import time
import requests
import re

二、下载函数

这个函数实际上包含了两个部分:一个是读取网页源代码,并从源代码里面筛选出小说内容;一部分是“爬”,这一部分是精髓。

def download(url, file_path):
    '''
    传入小说章节页面的网址,以及下载小说的路径。
    就可以下载小说,并且存储到指定路径的文件当中。
    返回下一章的网址
    '''
    #获得静态网页
    res = requests.get(url,params=req_header)
    res.encoding ='UTF-8'
    soups = BeautifulSoup(res.text,"html.parser")
    #选出章节标题,并进行处理
    title = str(soups.select('title'))
    title1 = re.sub(r'<[^>]+>|\xa0', '', title)
    c_title = title1.replace('_红楼春_穿越小说_笔趣阁', '')
    print(c_title)
    #选出章节内容,并进行处理
    content = str(soups.find_all('div',{'id':{'content'}}))
    content1 = re.sub(r'<[^>]+>','\r\n', content)
    c_content = re.sub(r'\xa0|\n[\s| ]*\r', '', content1)
    #将内容与标题写入文件
    f.write(c_title)
    f.write(c_content)
    #选出下一章链接
    bottem = soups.find('div',{'class':'bottem'}).find_all('a')[3]
    if 'href' in bottem.attrs:
        return bottem.attrs['href']

2.1下载本页小说

2.1.1、定位小说内容在哪里。

content = str(soups.find_all('div',{'id':{'content'}}))

图一
2.1.2、去除标签
在网页中小说内容全部都是加杂标签的,如下图。因此需要将标签去掉,去掉标签的方式就是使用正则表达式。

content1 = re.sub(r'<[^>]+>','\r\n', content)
c_content = re.sub(r'\xa0|\n[\s| ]*\r', '', content1)

图二
2.1.3、写入文件

    #将内容与标题写入文件
    f.write(c_title)
    f.write(c_content)

2.2“爬”

    #选出下一章链接
    bottem = soups.find('div',{'class':'bottem'}).find_all('a')[3]
    if 'href' in bottem.attrs:
        return bottem.attrs['href']

三、主体

if __name__ == "__main__":
	ua = UserAgent()
	req_header= {'User-Agent':ua.random}
    #定义基本信息字符串
    txt=['title','author','update','update1','Introduction']
    
    #小说章节目录url
    #仅在该网站上的小说:https://www.biquge.info/
    url = input("请输入小说主页网址:")
    #获得静态网页
    res = requests.get(url,params=req_header)
    res.encoding ='UTF-8'
    soups = BeautifulSoup(res.text,"html.parser")
    #小说主要信息获得
    txt[0] = '《'+ str(soups.h1) +'》'
    txt[1] = soups.select('#maininfo #info p')[0]   #info下第一个标签p的值
    txt[2] = soups.select('#maininfo #info p')[2]   #最新更新时间
    txt[3] = soups.select('#maininfo #info p')[3]   #最新更新章节
    txt[4] = soups.select('#maininfo #intro p')[0]  #小说简介

    txt[0] = re.sub(r'<[^>]+>', '', str(txt[0]))
    file_path = "D:\\BOX\\code\\python\\下载文件\\小说\\" + txt[0] + ".txt"
    f = open(file_path, 'a', encoding='utf-8')
    for i in [1, 2, 3, 4]:
        txt[i] = re.sub(r'<[^>]+>', '', str(txt[i]))
        #将小说信息录入文件
        f.write(txt[i]+'\n')
        if i == 4:
            f.write("********************"+'\n\n')
            
    #小说目录
    content = soups.select('#list dl dd')
    #小说总章数
    c_num = len(content)
    #实际下载小说章数
    c_num_1 = 0
    print(txt[0])
    print("小说共",c_num,"章。")
    #选出第一章url
    for link in content[0].find_all('a'):
        if 'href' in link.attrs:
            href = url + link.attrs['href']
    for k in range(c_num):
        href = download(href, file_path)
        c_num_1 = c_num_1+1
    if c_num_1 == c_num :
        print("全部下载完成,程序结束。")
    else :
        print("缺少章节。", c_num-c_num_1, "章。")
        print("实际已下载:", c_num_1, "章。")
    f.close()

四、全部程序

注意不同小说网站的爬取方式不一定相同,因此,需要根据实际的网站进行局部修改。
除此之外,文件储存路径也是需要修改的。

from fake_useragent import UserAgent
from bs4 import BeautifulSoup
import requests
import re
import random

def download(url, file_path):
    '''
    传入小说章节页面的网址,以及下载小说的路径。
    就可以下载小说,并且存储到指定路径的文件当中。
    返回下一章的网址
    '''
    #获得静态网页
    res = requests.get(url,params=req_header)
    res.encoding ='UTF-8'
    soups = BeautifulSoup(res.text,"html.parser")
    #选出章节标题,并进行处理
    title = str(soups.select('title'))
    title1 = re.sub(r'<[^>]+>|\xa0', '', title)
    c_title = title1.replace('_红楼春_穿越小说_笔趣阁', '')
    print(c_title)
    #选出章节内容,并进行处理
    content = str(soups.find_all('div',{'id':{'content'}}))
    content1 = re.sub(r'<[^>]+>','\r\n', content)
    c_content = re.sub(r'\xa0|\n[\s| ]*\r', '', content1)
    #选出下一章链接
    bottem = soups.find('div',{'class':'bottem'}).find_all('a')[3]
    #将内容与标题写入文件
    f.write(c_title)
    f.write(c_content)
    if 'href' in bottem.attrs:
        return bottem.attrs['href']

if __name__ == "__main__":
	ua = UserAgent()
	req_header= {'User-Agent':ua.random}
    #定义基本信息字符串
    txt=['title','author','update','update1','Introduction']
    
    #小说章节目录url
    #仅在该网站上的小说:https://www.biquge.info/
    url = input("请输入小说主页网址:")
    #获得静态网页
    res = requests.get(url,params=req_header)
    res.encoding ='UTF-8'
    soups = BeautifulSoup(res.text,"html.parser")
    #小说主要信息获得
    txt[0] = '《'+ str(soups.h1) +'》'
    txt[1] = soups.select('#maininfo #info p')[0]   #info下第一个标签p的值
    txt[2] = soups.select('#maininfo #info p')[2]   #最新更新时间
    txt[3] = soups.select('#maininfo #info p')[3]   #最新更新章节
    txt[4] = soups.select('#maininfo #intro p')[0]  #小说简介

    txt[0] = re.sub(r'<[^>]+>', '', str(txt[0]))
    file_path = "D:\\BOX\\code\\python\\下载文件\\小说\\" + txt[0] + ".txt"
    f = open(file_path, 'a', encoding='utf-8')
    for i in [1, 2, 3, 4]:
        txt[i] = re.sub(r'<[^>]+>', '', str(txt[i]))
        #将小说信息录入文件
        f.write(txt[i]+'\n')
        if i == 4:
            f.write("********************"+'\n\n')
            
    #小说目录
    content = soups.select('#list dl dd')
    #小说总章数
    c_num = len(content)
    #实际下载小说章数
    c_num_1 = 0
    print(txt[0])
    print("小说共",c_num,"章。")
    #选出第一章url
    for link in content[0].find_all('a'):
        if 'href' in link.attrs:
            href = url + link.attrs['href']
    for k in range(c_num):
        href = download(href, file_path)
        c_num_1 = c_num_1+1
    if c_num_1 == c_num :
        print("全部下载完成,程序结束。")
    else :
        print("缺少章节。", c_num-c_num_1, "章。")
        print("实际已下载:", c_num_1, "章。")
    f.close()

五、运行截图

1、获取网址
在这里插入图片描述2、运行程序,输入网址
在这里插入图片描述

3、程序结束
在这里插入图片描述

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

<think>为了爬取小说,我们需要选择一个小说网站,并分析其页面结构。这里以“笔趣阁”为例(注意:请确保遵守网站的使用条款,爬虫仅用于学习目的,且不要对网站造成过大压力)。 步骤: 1. 确定要爬取小说目录页URL。 2. 获取目录页的HTML,解析出所有章节的链接。 3. 遍历每个章节链接,获取章节内容。 4. 将章节内容保存到本地文件中。 我们将使用requests获取网页,使用BeautifulSoup解析HTML。 注意:有些网站有反爬机制,可能需要设置请求头(User-Agent)等。 示例:爬取《斗破苍穹》在笔趣阁中的小说。 假设目录页URL:`http://www.biquge.com.tw/0_1/` 由于网站可能变化,以下代码仅作为示例,实际使用时需要根据目标网站结构调整。 我们将: - 定义函数获取网页内容。 - 解析目录页,得到章节链接列表。 - 遍历每个章节,获取章节标题和正文。 - 将每个章节写入一个文本文件。 注意:为了避免请求过快被屏蔽,我们在每个请求之间加入短暂的延迟。 代码实现:</think>### Python爬取小说解决方案 我将使用`requests`获取网页内容,`BeautifulSoup`解析HTML,并添加反爬虫措施(随机User-Agent和延迟)。以下是完整代码: ```python import requests from bs4 import BeautifulSoup import time import random import re from fake_useragent import UserAgent def get_novel_content(novel_url): """爬取小说内容并保存到本地""" # 设置随机User-Agent ua = UserAgent() headers = {'User-Agent': ua.random} try: # 获取目录页 response = requests.get(novel_url, headers=headers, timeout=10) response.encoding = 'utf-8' soup = BeautifulSoup(response.text, 'html.parser') # 解析小说标题 novel_title = soup.find('h1').text.strip() print(f"开始爬取: 《{novel_title}》") # 解析章节链接 chapter_links = [] for link in soup.select('.listmain a'): if 'href' in link.attrs and '章' in link.text: chapter_links.append({ 'title': link.text.strip(), 'url': requests.compat.urljoin(novel_url, link['href']) }) # 创建保存文件 filename = f"{novel_title}.txt" with open(filename, 'w', encoding='utf-8') as f: f.write(f"《{novel_title}》\n\n") # 遍历所有章节 for i, chapter in enumerate(chapter_links): try: # 随机延迟防止被封(1-3秒) time.sleep(random.uniform(1, 3)) # 获取章节内容 chap_res = requests.get( chapter['url'], headers={'User-Agent': ua.random}, timeout=10 ) chap_res.encoding = 'utf-8' chap_soup = BeautifulSoup(chap_res.text, 'html.parser') # 提取正文内容 (根据网站结构调整选择器) content_div = chap_soup.select_one('#chaptercontent, .content, .novelcontent') if not content_div: print(f"警告: 未找到 {chapter['title']} 的正文") continue # 清理无用标签和广告 for tag in content_div.select('script, .adsbygoogle'): tag.decompose() # 处理文本格式 content = content_div.text.strip() content = re.sub(r'\s+', '\n', content) # 合并多余空白 content = re.sub(r'[\u3000]+', ' ', content) # 替换全角空格 # 写入文件 f.write(f"第{i+1}章 {chapter['title']}\n\n") f.write(content + "\n\n") f.flush() # 实时写入 print(f"已完成: {chapter['title']} ({i+1}/{len(chapter_links)})") except Exception as e: print(f"章节 {chapter['title']} 获取失败: {str(e)}") print(f"\n爬取完成! 文件已保存为: {filename}") return filename except Exception as e: print(f"爬取失败: {str(e)}") return None if __name__ == "__main__": # 示例URL (替换为目标小说目录页) novel_url = "https://www.biqg.cc/book/1/" get_novel_content(novel_url) ``` ### 代码详解 1. **反爬虫措施**: - `UserAgent().random`:每次请求使用随机User-Agent - `time.sleep(random.uniform(1, 3))`:章节间随机延迟 - `timeout=10`:设置请求超时 2. **核心功能**: - 目录页解析:通过CSS选择器`.listmain a`获取章节链接 - 内容清洗:删除广告标签(`script, .adsbygoogle`),正则表达式清理空白字符 - 编码处理:强制使用UTF-8编码防止乱码 3. **文件处理**: - 实时写入并`flush()`:防止意外中断丢失数据 - 章节标题编号:自动添加章节序号 4. **错误处理**: - 章节级异常捕获:单章失败不影响整体流程 - URL拼接:`urljoin`处理相对路径链接 ### 使用说明 1. 安装依赖: ```bash pip install requests beautifulsoup4 fake-useragent ``` 2. 修改目标URL: ```python novel_url = "https://www.example.com/novel/" # 替换为实际小说目录页 ``` 3. 常见网站适配调整: - **正文选择器**:修改`#chaptercontent`为目标网站的正文容器选择器 - **章节过滤**:修改`'章' in link.text`为实际章节标识 > ⚠️ 注意:请遵守目标网站的`robots.txt`规定,仅用于个人学习,避免高频访问造成服务器压力。
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值