Python實(shí)現(xiàn)博客快速備份的腳本分享
鑒于有些小伙伴在尋找博客園遷移到個(gè)人博客的方案,本人針對(duì)博客園實(shí)現(xiàn)了一個(gè)自動(dòng)備份腳本,可以快速將博客園中自己的文章備份成Markdown格式的獨(dú)立文件,備份后的md文件可以直接放入到hexo博客中,快速生成自己的站點(diǎn),而不需要自己逐篇文章遷移,提高了備份文章的效率。
首先第一步將博客園主題替換為codinglife
默認(rèn)主題,第二步登錄到自己的博客園后臺(tái),然后選擇博客備份
,備份所有的隨筆文章,如下所示:
備份出來(lái)以后將其命名為backup.xml
,然后新建一個(gè)main.py
腳本,以及一個(gè)blog
目錄,代碼實(shí)現(xiàn)的原理是,解析xml格式并依次提取出文檔內(nèi)容,然后分別保存為markdown文件。
轉(zhuǎn)存文章到MD
寫(xiě)入備份腳本,代碼如下所示,運(yùn)行后即可自動(dòng)轉(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: # 讀取時(shí)間 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檢測(cè) description_check = lines[0].replace("##","").replace("###","").replace("-","").replace("*","").replace("<br>","").replace(":","").replace(":","").replace(" ","").replace(" ","") if description_check == "": f.write("description: '{}'\n".format("該文章暫無(wú)概述")) elif description_check == "```C": f.write("description: '{}'\n".format("該文章暫無(wú)概述")) elif description_check == "```Python": f.write("description: '{}'\n".format("該文章暫無(wú)概述")) else: f.write("description: '{}'\n".format(description_check)) print("[*] 時(shí)間: {} --> 標(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")
備份后的效果如下所示:
打開(kāi)Markdown格式看一下,此處的標(biāo)簽和分類使用了一個(gè)別名,在備份下來(lái)以后,你可以逐個(gè)區(qū)域進(jìn)行替換,將其替換成自己需要的分類類型即可。
轉(zhuǎn)存圖片到本地
接著就是繼續(xù)循環(huán)將博客中所有圖片備份下來(lái),同樣新建一個(gè)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)頁(yè)編碼方式: {} -> {}".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)把博客備份下來(lái)以后你就可以把這些文章拷貝到hexo
博客_post
目錄下面,然后hexo
命令快速渲染生成博客園的鏡像站點(diǎn),這樣也算是增加雙保險(xiǎn)了。
到此這篇關(guān)于Python實(shí)現(xiàn)博客快速備份的腳本分享的文章就介紹到這了,更多相關(guān)Python備份博客內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)淘寶秒殺聚劃算搶購(gòu)自動(dòng)提醒源碼
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)淘寶秒殺聚劃算搶購(gòu)自動(dòng)提醒源碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02Python實(shí)現(xiàn)文本文件拆分寫(xiě)入到多個(gè)文本文件的方法
這篇文章主要介紹了Python實(shí)現(xiàn)文本文件拆分寫(xiě)入到多個(gè)文本文件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04如何理解python接口自動(dòng)化之logging日志模塊
代碼需要經(jīng)歷開(kāi)發(fā)、調(diào)試、審查、測(cè)試或者上線等不同階段,在“測(cè)試”時(shí),可能只想看警告和錯(cuò)誤信息,然而在“調(diào)試”時(shí),可能還想看到跟調(diào)試相關(guān)的信息。如果想打印出使用的模塊以及代碼運(yùn)行的時(shí)間,那么代碼很容易變得混亂。使用logging日志模塊,就能很容易地解決2021-06-06Python嵌套列表轉(zhuǎn)一維的方法(壓平嵌套列表)
今天小編就為大家分享一篇Python嵌套列表轉(zhuǎn)一維的方法(壓平嵌套列表),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07python讀取pdf格式文檔的實(shí)現(xiàn)代碼
這篇文章主要給大家介紹了關(guān)于python讀取pdf格式文檔的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04