Python實(shí)現(xiàn)博客快速備份的腳本分享
鑒于有些小伙伴在尋找博客園遷移到個人博客的方案,本人針對博客園實(shí)現(xiàn)了一個自動備份腳本,可以快速將博客園中自己的文章備份成Markdown格式的獨(dú)立文件,備份后的md文件可以直接放入到hexo博客中,快速生成自己的站點(diǎn),而不需要自己逐篇文章遷移,提高了備份文章的效率。
首先第一步將博客園主題替換為codinglife默認(rèn)主題,第二步登錄到自己的博客園后臺,然后選擇博客備份,備份所有的隨筆文章,如下所示:

備份出來以后將其命名為backup.xml,然后新建一個main.py腳本,以及一個blog目錄,代碼實(shí)現(xiàn)的原理是,解析xml格式并依次提取出文檔內(nèi)容,然后分別保存為markdown文件。

轉(zhuǎn)存文章到MD
寫入備份腳本,代碼如下所示,運(yùn)行后即可自動轉(zhuǎn)存文件到blog目錄下,當(dāng)運(yùn)行結(jié)束后備份也就結(jié)束了。
# 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"}
# 獲取文章,并轉(zhuǎn)成markdown
# blog: www.lyshark.com
def GetMarkDown(xml_file):
con = open(xml_file, 'r', encoding='utf8').read()
# 每篇文章都在 <item> 標(biāo)簽里
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 里面放的是文章的內(nèi)容
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("讀取狀態(tài): {}".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'\n")
except Exception:
f.write("date: '2018-12-27 00:00:00'\n")
pass
f.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("[*] 時間: {} --> 標(biāo)題: {}".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:
pass
if __name__ == "__main__":
GetMarkDown("backup.xml")
備份后的效果如下所示:

打開Markdown格式看一下,此處的標(biāo)簽和分類使用了一個別名,在備份下來以后,你可以逐個區(qū)域進(jìn)行替換,將其替換成自己需要的分類類型即可。

轉(zhuǎn)存圖片到本地
接著就是繼續(xù)循環(huán)將博客中所有圖片備份下來,同樣新建一個image文件夾,并運(yùn)行如下代碼實(shí)現(xiàn)備份。
# 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:
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("標(biāo)題: {} --> 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("網(wǎng)頁編碼方式: {} -> {}".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)
備份后的效果如下:

替換文章內(nèi)的圖片鏈接地址,可以使用編輯器,啟用正則批量替換。

當(dāng)把博客備份下來以后你就可以把這些文章拷貝到hexo博客_post目錄下面,然后hexo命令快速渲染生成博客園的鏡像站點(diǎn),這樣也算是增加雙保險了。

到此這篇關(guān)于Python實(shí)現(xiàn)博客快速備份的腳本分享的文章就介紹到這了,更多相關(guān)Python備份博客內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)淘寶秒殺聚劃算搶購自動提醒源碼
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)淘寶秒殺聚劃算搶購自動提醒源碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02
Python實(shí)現(xiàn)文本文件拆分寫入到多個文本文件的方法
這篇文章主要介紹了Python實(shí)現(xiàn)文本文件拆分寫入到多個文本文件的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python嵌套列表轉(zhuǎn)一維的方法(壓平嵌套列表)
今天小編就為大家分享一篇Python嵌套列表轉(zhuǎn)一維的方法(壓平嵌套列表),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
python讀取pdf格式文檔的實(shí)現(xiàn)代碼
這篇文章主要給大家介紹了關(guān)于python讀取pdf格式文檔的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

