CSDN文章保存为MD文档(二)

免责声明

文章仅做经验分享用途,利用本文章所提供的信息而造成的任何直接或者间接的后果及损失,均由使用者本人负责,作者不为此承担任何责任,一旦造成后果请自行承担!!!

import sys
sys.path.append("")
import requests
from bs4 import BeautifulSoup
from utils import Parser

def html2md(url, md_file, with_title=False):
    response = requests.get(url,headers = header)
    soup = BeautifulSoup(response.content, 'html.parser', from_encoding="utf-8")
    html = ""
    for child in soup.find_all('svg'):
        child.extract()
    if with_title:
        for c in soup.find_all('div', {'class': 'article-title-box'}):
            html += str(c)
    for c in soup.find_all('div', {'id': 'content_views'}):
        html += str(c)

    parser = Parser(html,markdown_dir)
    with open(md_file, 'w',encoding="utf-8") as f:
        f.write('{}\n'.format(''.join(parser.outputs)))
        
def download_csdn_single_page(article_url, md_dir, with_title=True, pdf_dir='pdf', to_pdf=False):
    response = requests.get(article_url,headers = header)
    soup = BeautifulSoup(response.content, 'html.parser', from_encoding="utf-8")
    title = soup.find_all('h1', {'class': 'title-article'})[0].string  ## 使用 html 的 title 作为 md 文件名
    title = title.replace('*', '').strip().split()
    md_file = md_dir+'/'+title[0] + '.md'
    print('Export Markdown File To {}'.format(md_file))
    html2md(article_url, md_file, with_title=with_title)

header = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,und;q=0.7",
        "Connection": "keep-alive",
        "Content-Type": "application/json;charset=UTF-8",
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36",
        "x-requested-with": "XMLHttpRequest"
        }

article_url = '' #csdn博客链接
markdown_dir = '' #保存文件夹
download_csdn_single_page(article_url,markdown_dir)

utils.py:

# -*- coding: utf-8 -*-
"""
Created on Wed Dec  1 10:10:19 2021

@author: Y
"""
from bs4 import BeautifulSoup, Tag, NavigableString, Comment
import os
from os.path import join, exists
import re
from urllib.request import urlretrieve
    

special_characters = {
    "&lt;": "<", "&gt;": ">", "&nbsp": " ",
    "&#8203": "",
}

class Parser(object):
    def __init__(self, html,markdown_dir):
        self.html = html
        self.soup = BeautifulSoup(html, 'html.parser')
        self.outputs = []
        self.fig_dir = markdown_dir
        self.pre = False
        self.equ_inline = False

        if not exists(self.fig_dir):
            os.makedirs(self.fig_dir)
        self.recursive(self.soup)

    def remove_comment(self, soup):
        if not hasattr(soup, 'children'): return
        for c in soup.children:
            if isinstance(c, Comment):
                c.extract()
            self.remove_comment(c)

    def recursive(self, soup):
        if isinstance(soup, Comment): return
        elif isinstance(soup, NavigableString):
            for key, val in special_characters.items():
                soup.string = soup.string.replace(key, val)
            self.outputs.append(soup.string)
        elif isinstance(soup, Tag):
            tag = soup.name
            if tag in ['h1', 'h2', 'h3', 'h4', 'h5']:
                n = int(tag[1])
                soup.contents.insert(0, NavigableString('\n' + '#'*n + ' '))
                soup.contents.append(NavigableString('\n'))
            elif tag == 'a' and 'href' in soup.attrs:
                soup.contents.insert(0, NavigableString('['))
                soup.contents.append(NavigableString("]({})".format(soup.attrs['href'])))
            elif tag in ['b', 'strong']:
                soup.contents.insert(0, NavigableString('**'))
                soup.contents.append(NavigableString('**'))
            elif tag in ['em']:
                soup.contents.insert(0, NavigableString('*'))
                soup.contents.append(NavigableString('*'))
            elif tag == 'pre':
                self.pre = True
            elif tag in ['code', 'tt']:
                if self.pre:
                    if not 'class' in soup.attrs:
                        language = 'bash'  # default language
                    else:
                        for name in ['cpp', 'bash', 'python', 'java']:
                            if name in ' '.join(list(soup.attrs['class'])): # <code class="prism language-cpp">
                                language = name
                    soup.contents.insert(0, NavigableString('\n```{}\n'.format(language)))
                    soup.contents.append(NavigableString('```\n'))
                    self.pre = False  # assume the contents of <pre> contain only one <code>
                else:
                    soup.contents.insert(0, NavigableString('`'))
                    soup.contents.append(NavigableString('`'))
            elif tag == 'p':
                if soup.parent.name != 'li':
                    # print(soup.parent)
                    soup.contents.insert(0, NavigableString('\n'))
            elif tag == 'span':
                if 'class' in soup.attrs:
                    if ('katex--inline' in soup.attrs['class'] or
                       'katex--display' in soup.attrs['class']): ## inline math
                        self.equ_inline = True if 'katex--inline' in soup.attrs['class'] else False
                        math_start_sign = '$' if self.equ_inline else '\n\n$$'
                        math_end_sign = '$' if self.equ_inline else '$$\n\n'
                        equation = soup.find_all('annotation', {'encoding': 'application/x-tex'})[0].string
                        equation = math_start_sign + str(equation) + math_end_sign
                        self.outputs.append(equation)
                        self.equ_inline = False
                        return
            elif tag in ['ol', 'ul']:
                soup.contents.insert(0, NavigableString('\n'))
                soup.contents.append(NavigableString('\n'))
            elif tag in ['li']:
                soup.contents.insert(0, NavigableString('+ '))
            # elif tag == 'blockquote':
                # soup.contents.insert(0, NavigableString('> '))
            elif tag == 'img':
                src = soup.attrs['src']
                # pattern = r'.*\.png'
                pattern = r'(.*\..*\?)|(.*\.(png|jpeg|jpg))'
                result_tuple = re.findall(pattern, src)[0]
                if result_tuple[0]:
                    img_file = result_tuple[0].split('/')[-1].rstrip('?')
                else:
                    img_file = result_tuple[1].split('/')[-1].rstrip('?')
                # img_file = re.findall(pattern, src)[0][0].split('/')[-1].rstrip('?') ## e.g. https://img-blog.csdnimg.cn/20200228210146931.png?
                img_file = join(self.fig_dir, img_file)
                # download_img_cmd = 'aria2c --file-allocation=none -c -x 10 -s 10 -o {} {}'.format(img_file, src)
                # if not exists(img_file):
                #     os.system(download_img_cmd)
                urlretrieve(src, img_file)
                # soup.attrs['src'] = img_file
                # self.outputs.append('\n' + str(soup.parent) + '\n')
                code = '![{}]({})'.format(img_file, img_file)
                self.outputs.append('\n' + code + '\n')
                return
        if not hasattr(soup, 'children'): return
        for child in soup.children:
            self.recursive(child)


if __name__ == '__main__':
    # html = '<body><!-- cde --><h1>This is 1 &lt;= 2<!-- abc --> <b>title</b></h1><p><a href="www.hello.com">hello</a></p><b>test</b>'
    html = '<body><!-- cde --><h1>hello</h1><h2>world</h2></body>'
    parser = Parser(html)
    print(''.join(parser.outputs))


结语

没有人规定,一朵花一定要成长为向日葵或者玫瑰。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/162339.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【HarmonyOS】 低代码平台组件拖拽使用技巧之登录组件

【关键字】 HarmonyOS、低代码平台、组件拖拽、登录组件、代码编辑器 1、写在前面 前面我们介绍了低代码中堆叠容器、滚动容器、网格布局、页签容器以及一些常用容器和组件的拖拽使用方法&#xff0c;本篇我们来介绍一个新的组件&#xff0c;这个组件是属于业务组件——登录组…

Modbus转Profinet网关:PLC与天信流量计通讯的经典案例

无论您是PLC或工业设备的制造商&#xff0c;还是工业自动化系统的维护人员&#xff0c;可能会遇到需要将不同协议的设备连接组合并通讯的情况&#xff0c;Modbus和Profinet是现代工业自动化中常见的两种通信协议&#xff0c;在工业控制领域中被广泛应用。 在这种情况绝大多数会…

快速上手Banana Pi BPI-M4 Zero 全志科技H618开源硬件开发开发板

Linux[编辑] 准备[编辑] 1. Linux镜像支持SD卡或EMMC启动&#xff0c;并且会优先从SD卡启动。 2. 建议使用A1级卡&#xff0c;至少8GB。 3. 如果您想从 SD 卡启动&#xff0c;请确保可启动 EMMC 已格式化。 4. 如果您想从 EMMC 启动并使用 Sdcard 作为存储&#xff0c;请确…

《微信小程序开发从入门到实战》学习二十六

3.4 开发参与投票页面 参与投票页面同样需要收集用户提交的信息&#xff0c;哪个用户在哪个投票选择了什么选项&#xff0c;因此它也是一个表单页面 3.4.1 如何获取投票信息 假设用户A在投票创建页面后填了表单&#xff08;1.创建投票&#xff09;&#xff0c;用户A 点了提交…

docker容器生成镜像并上传个人账户

登录到 Docker Hub 账户&#xff1a; docker login这将提示你输入你的 Docker Hub 账户名和密码。 为容器创建镜像 docker commit <容器名或容器ID> <你的用户名>/<镜像名:标签>例子 docker commit my_container yourusername/my_image:latest推送镜像到…

山西电力市场日前价格预测【2023-11-24】

日前价格预测 预测说明&#xff1a; 如上图所示&#xff0c;预测明日&#xff08;2023-11-24&#xff09;山西电力市场全天平均日前电价为415.13元/MWh。其中&#xff0c;最高日前电价为685.26元/MWh&#xff0c;预计出现在18:00。最低日前电价为296.84元/MWh&#xff0c;预计…

Web实战:基于Django与Bootstrap的在线计算器

文章目录 写在前面实验目标实验内容1. 创建项目2. 导入框架3. 配置项目前端代码后端代码 4. 运行项目 注意事项写在后面 写在前面 本期内容&#xff1a;基于Django与Bootstrap的在线计算器 实验环境&#xff1a; vscodepython(3.11.4)django(4.2.7)bootstrap(3.4.1)jquery(3…

美国DDoS服务器:如何保护你的网站免遭攻击?

​  在当今数字化时代&#xff0c;互联网已经成为人们生活中不可或缺的一部分。随着互联网的普及和发展&#xff0c;网络安全问题也日益严重。其中&#xff0c;DDoS攻击是目前最常见和具有破坏性的网络攻击之一。那么&#xff0c;如何保护你的网站免遭DDoS攻击呢?下面将介绍…

C#开发的OpenRA游戏之属性Selectable(9)

C#开发的OpenRA游戏之属性Selectable(9) 在游戏里,一个物品是否具有选中的能力,是通过添加属性Selectable来实现的。当一个物品不能被用户选取,那么就不要添加这个属性。 这个属性定义在下面这段描述里: ^Selectable: Selectable: SelectionDecorations: WithSpriteCon…

CSS画一条线

<p style"border: 1px solid rgba(0, 0, 0, 0.1);"></p> 效果&#xff1a;

MATLAB中imbothat函数用法

目录 语法 说明 示例 使用底帽和顶帽滤波增强对比度 imbothat函数的功能是对图像进行底帽滤波。 语法 J imbothat(I,SE) J imbothat(I,nhood) 说明 J imbothat(I,SE) 使用结构元素 SE 对灰度或二值图像 I 执行形态学底帽滤波。底帽滤波计算图像的形态学闭运算&#…

苹果手机内存满了怎么清理?这里有你想要的答案!

手机内存不足是一个比较普遍的现象。由于现在手机应用程序的功能越来越强大&#xff0c;所以占用的内存也越来越大。同时用户会在手机中存储大量的数据&#xff0c;如照片、视频、文档等&#xff0c;这些都会占用大量的手机空间。那么&#xff0c;苹果手机内存满了怎么清理&…

C++数组中重复的数字

3. 数组中重复的数字 题目链接 牛客网 题目描述 在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 Input: {2, 3, 1, 0, 2, 5}Output: 2解题…

Altium Designer学习笔记10

再次根据图纸进行布局走线&#xff1a; 这个MT2492 建议的布局走线。 那我这边应该是尽量按照该图进行布局&#xff1a; 其中我看到C1的电容的封装使用的是电感的封装&#xff0c;需要进行更换处理&#xff1a; 执行Validate Changes和Execute Changes操作&#xff0c;更新&a…

程序员最奔溃的瞬间

身为程序员哪一个瞬间让你最奔溃&#xff1f; *程序员最奔溃的瞬间&#xff0c; 勇士&#xff1f; or 无知&#xff1f;

Ant Design Pro生产环境部署

Ant Design Pro是通过URL路径前缀/api访问后端服务器&#xff0c;因此在nginx配置以下代理即可。 location / {index.html } location /api {proxy_pass: api.mydomain.com }

CSDN文章保存为MD文档(一)

免责声明 文章仅做经验分享用途&#xff0c;利用本文章所提供的信息而造成的任何直接或者间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c;作者不为此承担任何责任&#xff0c;一旦造成后果请自行承担&#xff01;&#xff01;&#xff01; import os import re i…

Element中el-table组件右侧空白隐藏-滚动条

开发情况&#xff1a; 固定table高度时&#xff0c;出现滚动条&#xff0c;我们希望隐藏滚动条&#xff0c;或修改滚动条样式&#xff0c;出现table右边出现15px 的固定留白。 代码示例 <el-table class"controlTable" header-row-class-name"controlHead…

C语言二十一弹 --打印空心正方形

C语言实现打印空心正方形 思路&#xff1a;观察图中空心正方形&#xff0c;可知首行列和尾行列被黑色外框包裹&#xff0c;其它均为空。所以按观察打印即可。 总代码 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h>int main() {int n 0;while (scanf("%d&q…

关于数据摆渡 你关心的5个问题都在这儿!

数据摆渡&#xff0c;这个词语的概念源自于网络隔离和数据交换的场景和需求。不管是物理隔离、协议隔离、应用隔离还是逻辑隔离&#xff0c;最终目的都是为了保护内部核心数据的安全。而隔离之后&#xff0c;又必然会存在文件交换的需求。 传统的跨网数据摆渡方式经历了从人工U…