Python 博客园快速备份脚本
鉴于有些小伙伴在寻找博客园迁移到个人博客的方案,本人针对博客园实现了一个自动备份脚本,可以快速将博客园中自己的文章备份成Markdown格式的独立文件,备份后的md文件可以直接放入到hexo博客中,快速生成自己的站点,而不需要自己逐篇文章迁移,提高了备份文章的效率。
首先第一步将博客园主题替换为codinglife
默认主题,第二步登录到自己的博客园后台,然后选择博客备份
,备份所有的随笔文章,如下所示:
备份出来以后将其命名为backup.xml
,然后新建一个main.py
脚本,以及一个blog
目录,代码实现的原理是,解析xml格式并依次提取出文档内容,然后分别保存为markdown文件。
转存文章到MD: 写入备份脚本,代码如下所示,运行后即可自动转存文件到blog目录
下,当运行结束后备份也就结束了。
# powerby: LyShark
# blog: www.cnblogs.com/lyshark
from bs4 import BeautifulSoup
import requests, os,reheader = {"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:title = re.findall(ele2[0], item, re.I | re.S | re.M)[0]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('\n')with open("./blog/" + title.replace("/","") + ".md", mode='w+', encoding='utf8') as f:f.write("---\n")f.write("title: '{}'\n".format(title.replace("##","").replace("###","").replace("-","").replace("*","").replace("<br>","").replace(":","").replace(":","").replace(" ","").replace(" ","").replace("`","")))f.write("copyright: true\n")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)passelse:f.write("date: '2018-12-27 00:00:00'\n")except Exception:f.write("date: '2018-12-27 00:00:00'\n")passf.write("date: '{}'\n".format(setdate))# description检测description_check = lines[0].replace("##","").replace("###","").replace("-","").replace("*","").replace("<br>","").replace(":","").replace(":","").replace(" ","").replace(" ","")if description_check == "":f.write("description: '{}'\n".format("该文章暂无概述"))elif description_check == "```C":f.write("description: '{}'\n".format("该文章暂无概述"))elif description_check == "```Python":f.write("description: '{}'\n".format("该文章暂无概述"))else:f.write("description: '{}'\n".format(description_check))print("[*] 时间: {} --> 标题: {}".format(setdate, title))f.write("tags: '{}'\n".format("tags10245"))f.write("categories: '{}'\n".format("categories10245"))f.write("---\n\n")f.write('%s' %des)f.close()except Exception:passif __name__ == "__main__":GetMarkDown("backup.xml")
备份后的效果如下所示:
打开Markdown格式看一下,此处的标签和分类使用了一个别名,在备份下来以后,你可以逐个区域进行替换,将其替换成自己需要的分类类型即可。
转存图片到本地: 接着就是继续循环将博客中所有图片备份下来,同样新建一个image文件夹
,并运行如下代码实现备份。
# powerby: LyShark
# blog: www.cnblogs.com/lyshark
from bs4 import BeautifulSoup
import requests, os,reheader = {"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:title = re.findall(ele2[0], item, re.I | re.S | re.M)[0]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))passexcept Exception:passif __name__ == "__main__":url = GetURL("backup.xml")for u in url:DownloadURLPicture(u)
备份后的效果如下:
替换文章内的图片链接地址,可以使用编辑器,启用正则批量替换。
当把博客备份下来以后你就可以把这些文章拷贝到hexo
博客_post
目录下面,然后hexo
命令快速渲染生成博客园的镜像站点,这样也算是增加双保险了。
Python 博客园快速备份脚本相关推荐
- python博客园_用Python向博客园发布新文章
最近在开发一个博客系统,经常把写的东西放在自己网站的博客上(之前写在Onenote),然后我在博客园也申请了一个博客,就有了同样一篇文章,我需要复制粘贴排版分别提交两次的情况.于是我就想能不能在我的网 ...
- python博客园、知乎、掘金爬取知乎文章及问答
bs主要爬取 def getSoup(url,herders):req = urllib.request.Request(url,headers=herders)response=urllib.req ...
- python博客园_python3 模拟博客园登录
'''作业题目: 模拟博客园登录 作业需求: 1),启动程序,首页面应该显示成如下格式: 欢迎来到博客园首页 1:请登录 2:请注册 3:文章页面 4:日记页面 5:评论页面 6:收藏页面 7:注销 ...
- python博客园_python模拟博客园登录-基础版
mport time import inspect from functools import wraps user_status = {'username': None,'status': Fals ...
- 派森学python_2019 年 1月 26 日 随笔档案 - 派森学python - 博客园
摘要:环境准备 python2.7 凑合的linux 差不多的无线网卡 "pywifi模块" 弱口令字典 清除系统中的任何wifi连接记录(非常重要!!!) 首先,这个模块在win ...
- 流浪的python博客园_python学习心得第一章
初始python 1什么是程序 计算机程序是一组执行某种动作的的指令.和那些电路.芯片.显卡.硬盘等不同,它不是计算机本身可以触摸的部分,而是隐藏在背后运行在硬件上面的东西.程序就是一系列告诉没有知觉 ...
- 流浪的python博客园_python学习心得第二章
python基础 1.关于python编码的问题. python的编码现在主要是两种版本python2.7和python3.5 python2.7默认的是ascii码进行编译,我们可以采用 # -*- ...
- 剑指offer python 博客园_python-剑指offer16-20
16.树 操作给定的二叉树,将其变换为源二叉树的镜像. #class TreeNode:#def __init__(self, x):#self.val = x#self.left = None#se ...
- 『Python开发实战菜鸟教程』实战篇:爬虫快速入门——统计分析CSDN与博客园博客阅读数据
文章目录 0x01:引子 首先介绍一下网络爬虫是什么,可以用来做什么? 这里简单探讨一下网络爬虫的合法性 正式进入爬虫实战前,需要我们了解下网页结构 HTML CSS JScript 写一个简单的 H ...
最新文章
- 客快物流大数据项目(十四):DockerFile介绍与构建过程解析
- linux 索引代码的函数定义,Linux网络接口操作之if_nameindex
- 进一步理解:inline-block,vertical-align,line-height
- 2020蓝桥杯省赛---java---A---10( 字串排序)
- ajax离开页面方法,如果用户在页面加载完成之前离开页面,则触发jQuery ajaxError()处理程序...
- LeetCode:892. 三维形体的表面积
- 信息学奥赛一本通(1171:大整数的因子)
- matlab瓶盖盖严检查,盖检机|瓶盖检测|外观检测设备|誉阵科技
- oracle主键id自动自增_Oracle主键ID设置自动增长(序列+触发器)
- 理解认证_授权_以及会话_Spring Security OAuth2.0认证授权---springcloud工作笔记110
- 万能点位图软件_万能点位图软件_BoardViewer
- 关于php开发中用户请求数据的安全问题的一点想法
- 二叉树模型matlab实现,利用Matlab实现二叉树的树形显示
- excel两个表格数据对比_表格技巧—Excel表格两列数据合并
- 小米手机获取root权限最常见问题
- IELTS11 Test2 laws are needed to make people recycle more of their waste
- 永久禁用software reporter 进程,占用高解决方法。【永久禁用software_reporter_tool.exe程序】
- Python学习:输出99乘法口诀表
- iOSUILable边距设置
- Photoshop cs8 颜色 查看调出 hsb模式滑块