用python写了个程序,可以将csdn博客的文章备份到本地,使用的时候只需要输入自己博客首页的地址,程序就会在当前目录下建立“csdn备份”文件夹,然后将该博客里面的所有文章下载到该文件夹下面。
python版本为3.3.3,使用时需要安装该版本的python解释器。
from urllib import request
import re
import os
import time
#加上头信息,伪装成浏览器访问
def getContent(URL):
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
req=request.Request(URL, headers=headers)
content=request.urlopen(req).read().decode('utf-8')
return content;
def getAllBlogLinks(URL):
"""获得所有博文的链接"""
nextPageURL=URL;
blogs=[];
while nextPageURL!=None:
content=getContent(nextPageURL)
blogPattern="""class="link_title"><a href="(.*)">[\\s]+(.*?)[\\s]+</a>""" #正则表达式匹配文章链接和题目
blogPatternObj=re.compile(blogPattern);
tempBlogs=blogPatternObj.findall(content)
blogs=blogs+tempBlogs;
nextPagePattern=""".*<a href="(.*?)">下一页</a>""" #找下一页的链接
nextPagePatternObj=re.compile(nextPagePattern)
nextPage=nextPagePatternObj.findall(content)
if len(nextPage):
nextPageURL=nextPage[0]
nextPageURL=r"http://blog.csdn.net/"+nextPageURL;
# print(nextPageURL)
else:
nextPageURL=None
return blogs
def downLoadBlogs(blogs):
dir="""csdn备份"""
if not os.path.exists(dir):
os.mkdir(dir)
for blog in blogs:
time.sleep(1); #延时一秒,过快的访问会引起502 bad gateway 错误
blogURL=blog[0]
blogTitle=blog[1]
blogURL=r"http://blog.csdn.net/"+blogURL
print(blogURL)
print(blogTitle)
content=getContent(blogURL)
mainBodyPattern="""<div id="article_content" class="article_content">[\\s\\S]*?<!-- Baidu Button BEGIN -->"""
mainBodyPatternObj=re.compile(mainBodyPattern)
mainBody=mainBodyPatternObj.findall(content);
filename=blogTitle
file=open(dir+'/'+filename+'.html', 'wb')
file.write(mainBody[0].encode('utf8')) #若使用浏览器查看出现乱码,请将浏览器解码方式更改为utf8
file.close()
picturePattern="""<img src="(http:.*?)"[\\s\\S]*?alt"""
picturePatternObj=re.compile(picturePattern);
pictures=picturePatternObj.findall(mainBody[0])
if len(pictures)!=0:
pictureDir=dir+'/'+filename;
if not os.path.exists(pictureDir):
os.mkdir(pictureDir)
i=0;
for pictureURL in pictures:
pictureName=blogTitle+"_picture_"+str(i)
request.urlretrieve(pictureURL, pictureDir+'/'+pictureName)
i=i+1
#主程序
print("please type in your blog link") #输入自己博客首页的地址即可
blogLink=input()
print(blogLink)
blogs=getAllBlogLinks(blogLink)
downLoadBlogs(blogs)
看看执行的效果: