当前位置: 代码网 > it编程>前端脚本>Python > Python实现网页内容转纯文本与EPUB电子书的完整指南

Python实现网页内容转纯文本与EPUB电子书的完整指南

2026年02月03日 Python 我要评论
在信息爆炸的时代,我们每天都会浏览大量网页内容。无论是新闻资讯、技术教程还是小说文学,如何将这些分散的网页内容高效保存并离线阅读,成为现代人的刚需。本文将通过python实现两种主流保存方案:纯文本格

在信息爆炸的时代,我们每天都会浏览大量网页内容。无论是新闻资讯、技术教程还是小说文学,如何将这些分散的网页内容高效保存并离线阅读,成为现代人的刚需。本文将通过python实现两种主流保存方案:纯文本格式(txt)和电子书标准格式(epub),并提供完整代码与实战案例。

一、技术选型与工具准备

1.1 核心工具链

  • 网页抓取requests库(http请求)
  • html解析beautifulsoup(静态内容解析)
  • 电子书生成ebooklib(epub标准支持)
  • 动态内容处理selenium(可选,应对javascript渲染)

1.2 环境配置

pip install requests beautifulsoup4 lxml ebooklib selenium

注:若需处理动 态网页,还需下载对应浏览器的webdriver(如chromedriver)

二、网页内容提取技术

2.1 基础抓取流程

import requests
from bs4 import beautifulsoup

def fetch_webpage(url):
    headers = {'user-agent': 'mozilla/5.0'}
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # 异常处理
    return response.content

2.2 智能正文提取算法

通过分析100+新闻/博客网站结构,总结出以下高效提取策略:

def extract_content(html):
    soup = beautifulsoup(html, 'lxml')
    
    # 优先匹配常见正文容器
    selectors = ['article', 'main', '.post-content', '#content']
    for selector in selectors:
        content = soup.select_one(selector)
        if content:
            return clean_content(content)
    
    # 回退方案:提取所有段落
    paragraphs = soup.find_all('p')
    if paragraphs:
        return '\n\n'.join(p.get_text() for p in paragraphs)
    
    return "提取失败"

def clean_content(element):
    # 移除广告/分享按钮等干扰元素
    for tag in ['script', 'style', 'iframe', 'nav', 'footer']:
        for item in element.find_all(tag):
            item.decompose()
    return '\n\n'.join(p.get_text() for p in element.find_all('p'))

实战案例:提取csdn博客正文

url = "https://blog.csdn.net/example/article/details/123456"
html = fetch_webpage(url)
content = extract_content(html)
print(content[:200])  # 预览前200字符

三、纯文本保存方案

3.1 基础实现

def save_as_txt(title, content, filename=none):
    if not filename:
        safe_title = "".join(c for c in title if c.isalnum() or c in (' ', '_'))[:50]
        filename = f"{safe_title}.txt"
    
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(f"【标题】{title}\n\n")
        f.write(content)
    print(f"✅ 保存成功: {filename}")

3.2 增强功能

  • 自动分章节:通过标题标签(h1-h6)分割内容
  • 编码优化:处理特殊字符与换行符
  • 批量处理:爬取多篇文章合并保存

完整示例

def advanced_txt_save(url):
    html = fetch_webpage(url)
    soup = beautifulsoup(html, 'lxml')
    
    # 提取标题与正文
    title = soup.title.string if soup.title else "无标题"
    content = extract_content(html)
    
    # 自动分章节(示例:按h2分割)
    chapters = []
    current_chapter = ""
    for element in soup.body.descendants:
        if element.name == 'h2':
            if current_chapter:
                chapters.append(current_chapter)
            current_chapter = f"\n\n{element.get_text()}\n"
        elif element.name == 'p' and current_chapter is not none:
            current_chapter += f"{element.get_text()}\n"
    if current_chapter:
        chapters.append(current_chapter)
    
    # 保存
    with open(f"{title}.txt", 'w', encoding='utf-8') as f:
        f.write(f"【全文目录】\n")
        for i, chap in enumerate(chapters, 1):
            f.write(f"{i}. {chap.split('\n')[0]}\n")
        f.write("\n" + "\n".join(chapters))

四、epub电子书生成技术

4.1 epub标准解析

epub是国际数字出版论坛(idpf)制定的开放标准,具有三大核心组件:

  • 内容文档:xhtml格式的章节文件
  • 包装文件:opf(open packaging format)
  • 导航文件:ncx(navigation control file)

4.2 基础生成代码

from ebooklib import epub

def create_epub(title, author, content):
    book = epub.epubbook()
    book.set_identifier('id123456')
    book.set_title(title)
    book.set_language('zh-cn')
    book.add_author(author)
    
    # 创建章节
    chapter = epub.epubhtml(
        title=title,
        file_name='content.xhtml',
        lang='zh'
    )
    html_content = f"""
    <html>
        <head>
            <title>{title}</title>
            <style>
                body {{ font-family: "simsun"; line-height: 1.6; }}
                h1 {{ text-align: center; }}
                p {{ text-indent: 2em; margin: 0.5em 0; }}
            </style>
        </head>
        <body>
            <h1>{title}</h1>
            {"".join(f"<p>{para}</p>" for para in content.split('\n\n') if para.strip())}
        </body>
    </html>
    """
    chapter.set_content(html_content)
    book.add_item(chapter)
    
    # 设置目录
    book.toc = [epub.link('content.xhtml', title, 'intro')]
    book.spine = ['nav', chapter]
    
    # 添加导航文件
    book.add_item(epub.epubncx())
    book.add_item(epub.epubnav())
    
    return book

def save_epub(book, filename=none):
    if not filename:
        filename = f"{book.title[:50]}.epub"
    epub.write_epub(filename, book)
    print(f"✅ epub生成成功: {filename}")

4.3 高级功能实现

案例:多章节小说生成

def novel_to_epub(url_template, chapters):
    book = epub.epubbook()
    book.set_identifier('novel123')
    book.set_title("示例小说")
    book.set_language('zh')
    book.add_author("佚名")
    
    # 批量添加章节
    for i, chap_num in enumerate(chapters, 1):
        url = url_template.format(chap_num)
        html = fetch_webpage(url)
        soup = beautifulsoup(html, 'lxml')
        
        # 假设每章标题在h1标签
        title = soup.h1.get_text() if soup.h1 else f"第{chap_num}章"
        content = clean_content(soup)
        
        chapter = epub.epubhtml(
            title=title,
            file_name=f"chap_{i}.xhtml"
        )
        chapter.set_content(f"""
        <html>
            <body>
                <h2>{title}</h2>
                {"".join(f"<p>{para}</p>" for para in content.split('\n\n') if para.strip())}
            </body>
        </html>
        """)
        book.add_item(chapter)
        book.toc.append(epub.link(f"chap_{i}.xhtml", title, f"chap{i}"))
    
    book.spine = ['nav'] + [epub.spineitem(ref=f"chap_{i}.xhtml") for i in range(1, len(chapters)+1)]
    save_epub(book)

# 使用示例
novel_to_epub("https://example.com/novel/chapter_{}.html", range(1, 21))

五、实战综合案例

5.1 需求场景

将知乎专栏的多篇文章合并保存为epub,要求:

  • 自动抓取指定专栏的所有文章
  • 保留原文格式与图片
  • 生成可跳转的目录

5.2 解决方案

import os
from urllib.parse import urljoin

def zhihu_column_to_epub(column_url):
    # 1. 获取专栏文章列表(简化版,实际需分析知乎api)
    html = fetch_webpage(column_url)
    soup = beautifulsoup(html, 'lxml')
    article_links = [urljoin(column_url, a['href']) 
                    for a in soup.select('.list-itemtitle a[href^="/p/"]')[:5]]  # 取前5篇示例
    
    # 2. 创建epub容器
    book = epub.epubbook()
    book.set_identifier('zhihu123')
    column_title = soup.select_one('.columnheader-title').get_text().strip()
    book.set_title(column_title)
    book.set_language('zh')
    book.add_author("知乎用户")
    
    # 3. 处理每篇文章
    for i, url in enumerate(article_links, 1):
        article_html = fetch_webpage(url)
        article_soup = beautifulsoup(article_html, 'lxml')
        
        # 提取标题与正文
        title = article_soup.select_one('h1.post-title').get_text().strip()
        content_div = article_soup.select_one('.post-richtext')
        
        # 处理图片(保存到本地并修改路径)
        img_dir = f"images_{i}"
        os.makedirs(img_dir, exist_ok=true)
        for img in content_div.find_all('img'):
            img_url = urljoin(url, img['src'])
            img_data = requests.get(img_url).content
            img_name = img['src'].split('/')[-1]
            with open(f"{img_dir}/{img_name}", 'wb') as f:
                f.write(img_data)
            img['src'] = f"{img_dir}/{img_name}"
        
        # 生成章节
        chapter = epub.epubhtml(
            title=title,
            file_name=f"article_{i}.xhtml"
        )
        chapter.set_content(f"""
        <html>
            <head>
                <style>
                    body {{ max-width: 800px; margin: 0 auto; font-family: "simsun"; }}
                    img {{ max-width: 100%; height: auto; }}
                </style>
            </head>
            <body>
                <h1>{title}</h1>
                {str(content_div)}
            </body>
        </html>
        """)
        book.add_item(chapter)
        book.toc.append(epub.link(f"article_{i}.xhtml", title, f"art{i}"))
    
    # 4. 生成epub
    book.spine = ['nav'] + [epub.spineitem(ref=f"article_{i}.xhtml") for i in range(1, len(article_links)+1)]
    save_epub(book, f"{column_title}.epub")

# 使用示例
zhihu_column_to_epub("https://zhuanlan.zhihu.com/example")

六、性能优化与异常处理

6.1 常见问题解决方案

问题类型解决方案
反爬机制设置user-agent,使用代理ip池
动态内容结合selenium渲染javascript
编码错误强制指定response.encoding='utf-8'
大文件处理使用流式下载与分块处理

6.2 完整异常处理框架

def safe_fetch(url, max_retries=3):
    for _ in range(max_retries):
        try:
            headers = {'user-agent': 'mozilla/5.0'}
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()
            response.encoding = 'utf-8'
            return response.content
        except requests.exceptions.requestexception as e:
            print(f"请求失败: {e}")
            continue
    raise runtimeerror(f"超过最大重试次数: {url}")

七、总结与扩展

7.1 技术价值

  • 知识管理:将碎片化网页内容系统化保存
  • 阅读体验:epub格式支持字体调整、书签、夜间模式等
  • 跨平台:生成的电子书可在kindle、ios/android设备无缝阅读

7.2 扩展方向

  • 自动化爬虫:结合scrapy框架实现大规模内容抓取
  • 增强排版:使用weasyprint将html转为pdf
  • 云存储:集成aws s3或阿里云oss实现自动备份
  • ai增强:通过nlp技术自动生成摘要与关键词

通过本文介绍的技术方案,读者可以轻松构建自己的网页内容保存系统。无论是简单的txt备份,还是专业的epub电子书制作,python都能提供高效可靠的解决方案。实际开发中,建议根据具体需求选择合适的技术组合,并始终遵守目标网站的robots.txt协议与版权法规。

到此这篇关于python实现网页内容转纯文本与epub电子书的完整指南的文章就介绍到这了,更多相关python网页内容转文本与epub内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com