脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现博客快速备份的脚本分享

Python实现博客快速备份的脚本分享

2022-09-04 17:00lyshark Python

本文针对博客园实现了一个自动备份脚本,可以快速将自己的文章备份成Markdown格式的独立文件,备份后的md文件可以直接放入到hexo博客中,感兴趣的可以了解一下

鉴于有些小伙伴在寻找博客园迁移到个人博客的方案,本人针对博客园实现了一个自动备份脚本,可以快速将博客园中自己的文章备份成Markdown格式的独立文件,备份后的md文件可以直接放入到hexo博客中,快速生成自己的站点,而不需要自己逐篇文章迁移,提高了备份文章的效率。

首先第一步将博客园主题替换为codinglife默认主题,第二步登录到自己的博客园后台,然后选择博客备份,备份所有的随笔文章,如下所示:

Python实现博客快速备份的脚本分享

备份出来以后将其命名为backup.xml,然后新建一个main.py脚本,以及一个blog目录,代码实现的原理是,解析xml格式并依次提取出文档内容,然后分别保存为markdown文件。

Python实现博客快速备份的脚本分享

转存文章到MD

写入备份脚本,代码如下所示,运行后即可自动转存文件到blog目录下,当运行结束后备份也就结束了。

# powerby: LyShark
# blog: www.cnblogs.com/lyshark
from bs4 import BeautifulSoup
import requests, os,re

header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) By LyShark CnblogsBlog Backup Script"}

# 获取文章,并转成markdown
# blog: www.lyshark.com
def GetMarkDown(xml_file):
    con = open(xml_file, "r", encoding="utf8").read()
    # 每篇文章都在 <item> 标签里
    items = re.findall("<item>.*?</item>", con, re.I | re.M | re.S)
    ele2 = ["<title>(.+?)</title>", "<link>(.+?)</link>", "<description>(.+?)</description>"]
    # md_name = xml_file.split(".xml")[0] + ".md"
    for item in items:
        try:
            link = re.findall(ele2[1], item, re.I | re.S | re.M)[0]
            des = re.findall(ele2[2], item, re.I | re.S | re.M)[0]
            des = re.findall("<![CDATA[(.+?)]]>", des, re.I | re.S | re.M)[0]  # CDATA 里面放的是文章的内容
            des = des.replace("~~~", "```")
            lines = des.split("
")
            with open("./blog/" + title.replace("/","") + ".md", mode="w+", encoding="utf8") as f:
                f.write("---
")
                f.write("title: "{}"
".format(title.replace("##","").replace("###","").replace("-","").replace("*","").replace("<br>","").replace(":","").replace(":","").replace(" ","").replace(" ","").replace("`","")))
                f.write("copyright: true
")

                setdate = "2018-12-27 00:00:00"
                try:
                    # 读取时间
                    response = requests.get(url=link, headers=header)
                    print("读取状态: {}".format(response.status_code))

                    if response.status_code == 200:
                        bs = BeautifulSoup(response.text, "html.parser")
                        ret = bs.select("span[id="post-date"]")[0]
                        setdate = str(ret.text)
                        pass
                    else:
                        f.write("date: "2018-12-27 00:00:00"
")
                except Exception:
                    f.write("date: "2018-12-27 00:00:00"
")
                    pass

                f.write("date: "{}"
".format(setdate))

                # description检测
                description_check = lines[0].replace("##","").replace("###","").replace("-","").replace("*","").replace("<br>","").replace(":","").replace(":","").replace(" ","").replace(" ","")
                if description_check == "":
                    f.write("description: "{}"
".format("该文章暂无概述"))
                elif description_check == "```C":
                    f.write("description: "{}"
".format("该文章暂无概述"))
                elif description_check == "```Python":
                    f.write("description: "{}"
".format("该文章暂无概述"))
                else:
                    f.write("description: "{}"
".format(description_check))

                print("[*] 时间: {} --> 标题: {}".format(setdate, title))
                f.write("tags: "{}"
".format("tags10245"))
                f.write("categories: "{}"
".format("categories10245"))
                f.write("---

")
                f.write("%s" %des)
                f.close()
        except Exception:
            pass

if __name__ == "__main__":
    GetMarkDown("backup.xml")

备份后的效果如下所示:

Python实现博客快速备份的脚本分享

打开Markdown格式看一下,此处的标签和分类使用了一个别名,在备份下来以后,你可以逐个区域进行替换,将其替换成自己需要的分类类型即可。

Python实现博客快速备份的脚本分享

转存图片到本地

接着就是继续循环将博客中所有图片备份下来,同样新建一个image文件夹,并运行如下代码实现备份。

# powerby: LyShark
# blog: www.cnblogs.com/lyshark
from bs4 import BeautifulSoup
import requests, os,re

header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) By LyShark CnblogsBlog Backup Script"}

# 从备份XML中找到URL
# blog: www.cnblogs.com/lyshark
def GetURL(xml_file):
    blog_url = []
    con = open(xml_file, "r", encoding="utf8").read()
    items = re.findall("<item>.*?</item>", con, re.I | re.M | re.S)
    ele2 = ["<title>(.+?)</title>", "<link>(.+?)</link>", "<description>(.+?)</description>"]
    for item in items:
        link = re.findall(ele2[1], item, re.I | re.S | re.M)[0]
        print("标题: {} --> URL: {} ".format(title,link))
        blog_url.append(link)
    return blog_url

# 下载所有图片
# blog: www.lyshark.com
def DownloadURLPicture(url):
    params = {"encode": "utf-8"}
    response = requests.get(url=url, params=params, headers=header)
    # print("网页编码方式: {} -> {}".format(response.encoding,response.apparent_encoding))
    context = response.text.encode(response.encoding).decode(response.apparent_encoding, "ignore")
    try:
        bs = BeautifulSoup(context, "html.parser")
        ret = bs.select("div[id="cnblogs_post_body"] p img")
        for item in ret:
            try:
                img_src_path = item.get("src")
                img_src_name = img_src_path.split("/")[-1]
                print("[+] 下载图片: {} ".format(img_src_name))
                img_download = requests.get(url=img_src_path, headers=header, stream=True)
                with open("./image/" + img_src_name, "wb") as fp:
                    for chunk in img_download.iter_content(chunk_size=1024):
                        fp.write(chunk)
            except Exception:
                print("下载图片失败: {}".format(img_src_name))
                pass
    except Exception:
        pass

if __name__ == "__main__":
    url = GetURL("backup.xml")
    for u in url:
        DownloadURLPicture(u)

备份后的效果如下:

Python实现博客快速备份的脚本分享

替换文章内的图片链接地址,可以使用编辑器,启用正则批量替换。

Python实现博客快速备份的脚本分享

当把博客备份下来以后你就可以把这些文章拷贝到hexo博客_post目录下面,然后hexo命令快速渲染生成博客园的镜像站点,这样也算是增加双保险了。

Python实现博客快速备份的脚本分享

到此这篇关于Python实现博客快速备份的脚本分享的文章就介绍到这了,更多相关Python备份博客内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://www.cnblogs.com/LyShark/p/16652464.html

延伸 · 阅读

精彩推荐
  • PythonPython安装xarray库读取.nc文件的详细步骤

    Python安装xarray库读取.nc文件的详细步骤

    大家应该都知道库xarray可以帮我们读取出nc文件的内容,所以下面这篇文章主要给大家介绍了关于Python安装xarray读取.nc文件的详细步骤,文中通过实例代码介绍...

    焦糖呱呱子10772022-07-21
  • Pythonpython类和继承用法实例

    python类和继承用法实例

    这篇文章主要介绍了python类和继承用法,实例分析了Python类的定义与继承的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    defias2522020-07-20
  • PythonOpenCV图像处理之自定义滤波

    OpenCV图像处理之自定义滤波

    滤波处理分为两大类:线性滤波和非线性滤波,OpenCV里有这些滤波的函数,使用起来非常方便,这篇文章主要给大家介绍了关于OpenCV图像处理之自定义滤波的相...

    飞鸢逐浪8412021-12-24
  • PythonPython Requests 基础入门

    Python Requests 基础入门

    首先,Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 不友好。通过本文给大家介绍Python Requests 入门基础,感兴趣的朋友一起...

    waited2412020-08-18
  • PythonPython文件和目录操作详解

    Python文件和目录操作详解

    这篇文章主要介绍了Python文件和目录操作详解,本文讲解了文件的打开和创建、文件的读取、文件的写入、内容查找替换等内容,需要的朋友可以参考下 ...

    junjie3522019-11-17
  • PythonWindows下pycharm安装第三方库失败(通用解决方案)

    Windows下pycharm安装第三方库失败(通用解决方案)

    这篇文章主要介绍了Windows下pycharm安装第三方库失败(通用解决方案),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,...

    Encin_Li6532020-09-17
  • Pythonpython基础教程项目四之新闻聚合

    python基础教程项目四之新闻聚合

    这篇文章主要为大家详细介绍了python基础教程项目四之新闻聚合,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    the5fire8182021-01-26
  • PythonDjango利用cookie保存用户登录信息的简单实现方法

    Django利用cookie保存用户登录信息的简单实现方法

    这篇文章主要介绍了Django利用cookie保存用户登录信息的简单实现方法,结合实例形式分析了Django框架使用cookie保存用户信息的相关操作技巧,需要的朋友可以...

    学习笔记6669522021-06-30