- Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathExportCSDNBlog.py
More file actions
Latest commit
executable file
·297 lines (248 loc) · 9.73 KB
/
Copy pathExportCSDNBlog.py
File metadata and controls
executable file
·297 lines (248 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#! encoding=utf-8
# Author : kesalin@gmail.com
# Blog : http://kesalin.github.io
# Date : 2014/10/18
# Description : Export CSND blog articles to Markdown files.
# Version : 1.0.0.0
# Python Version: Python 2.7.3
#
importurllib2
importre
importos
importsys
importdatetime
importtime
importtraceback
importcodecs
frombs4importBeautifulSoup
#===========================================================================
# set your CSDN username
__username__="kesalin"
# set output dir
__output__="C:/Code/Python"
enableLog=True
# for test
#__testArticleUrl__ = "http://blog.csdn.net/kesalin/article/details/5414998"
#===========================================================================
# 尝试获取资源次数
gRetryCount=5
header= {"User-Agent": "Mozilla-Firefox5.0"}
deflog(str):
ifenableLog:
printstr
newFile=open('log.txt', 'a+')
newFile.write(str+'\n')
newFile.close()
defdecodeHtmlSpecialCharacter(htmlStr):
specChars= {" " : "", \
" " : "", \
" " : "", \
"<" : "<", \
">" : ">", \
"&" : "&", \
""" : "\"", \
"©" : "®", \
"×" : "×", \
"÷" : "÷", \
}
forkeyinspecChars.keys():
htmlStr=htmlStr.replace(key, specChars[key])
returnhtmlStr
defrepalceInvalidCharInFilename(filename):
specChars= {"\\" : "", \
"/" : "", \
":" : "", \
"*" : "", \
"?" : "", \
"\"" : "", \
"<" : "小于", \
">" : "大于", \
"|" : " and ", \
"&" :" or ", \
}
forkeyinspecChars.keys():
filename=filename.replace(key, specChars[key])
returnfilename
# process html content to markdown content
defhtmlContent2String(contentStr):
patternImg=re.compile(r'(<img.+?src=")(.+?)(".+ />)')
patternHref=re.compile(r'(<a.+?href=")(.+?)(".+?>)(.+?)(</a>)')
patternRemoveHtml=re.compile(r'</?[^>]+>')
resultContent=patternImg.sub(r'', contentStr)
resultContent=patternHref.sub(r'[\4](\2)', resultContent)
resultContent=re.sub(patternRemoveHtml, r'', resultContent)
resultContent=decodeHtmlSpecialCharacter(resultContent)
returnresultContent
defexportToMarkdown(exportDir, postdate, categories, title, content):
titleDate=postdate.strftime('%Y-%m-%d')
contentDate=postdate.strftime('%Y-%m-%d %H:%M:%S %z')
filename=titleDate+'-'+title
filename=repalceInvalidCharInFilename(filename)
filepath=exportDir+'/'+filename+'.markdown'
log(" >> save as "+filename)
newFile=open(unicode(filepath, "utf8"), 'w')
newFile.write('---'+'\n')
newFile.write('layout: post'+'\n')
newFile.write('title: \"'+title+'\"\n')
newFile.write('date: '+contentDate+'\n')
newFile.write('comments: true'+'\n')
newFile.write('categories: ['+categories+']'+'\n')
newFile.write('tags: ['+categories+']'+'\n')
newFile.write('description: \"'+title+'\"\n')
newFile.write('keywords: '+categories+'\n')
newFile.write('---'+'\n\n')
newFile.write(content)
newFile.write('\n')
newFile.close()
defdownload(url, output):
# 下载文章,并保存为 markdown 格式
log(" >> download: "+url)
data=None
title=""
categories=""
content=""
postDate=datetime.datetime.now()
globalgRetryCount
count=0
whileTrue:
ifcount>=gRetryCount:
break
count=count+1
try:
time.sleep(2.0) #访问太快会不响应
request=urllib2.Request(url, None, header)
response=urllib2.urlopen(request)
data=response.read().decode('UTF-8')
break
exceptException,e:
exstr=traceback.format_exc()
log(" >> failed to download "+url+", retry: "+str(count) +", error:"+exstr)
pass
ifdata==None:
log(" >> failed to download "+url)
return
#print data
soup=BeautifulSoup(data)
topTile="[置顶]"
titleDocs=soup.find_all("div", "article_title")
fortitleDocintitleDocs:
titleStr=titleDoc.a.get_text().encode('UTF-8')
title=titleStr.replace(topTile, '').strip()
#log(" >> title: " + title)
manageDocs=soup.find_all("div", "article_manage")
formanagerDocinmanageDocs:
categoryDoc=managerDoc.find_all("span", "link_categories")
iflen(categoryDoc) >0:
categories=categoryDoc[0].a.get_text().encode('UTF-8').strip()
postDateDoc=managerDoc.find_all("span", "link_postdate")
iflen(postDateDoc) >0:
postDateStr=postDateDoc[0].string.encode('UTF-8').strip()
postDate=datetime.datetime.strptime(postDateStr, '%Y-%m-%d %H:%M')
contentDocs=soup.find_all(id="article_content")
forcontentDocincontentDocs:
htmlContent=contentDoc.prettify().encode('UTF-8')
content=htmlContent2String(htmlContent)
exportToMarkdown(output, postDate, categories, title, content)
defgetPageUrlList(url):
# 获取所有的页面的 url
request=urllib2.Request(url, None, header)
response=urllib2.urlopen(request)
data=response.read()
#print data
soup=BeautifulSoup(data)
lastArticleHref=None
pageListDocs=soup.find_all(id="papelist")
forpageListinpageListDocs:
hrefDocs=pageList.find_all("a")
iflen(hrefDocs) >0:
lastArticleHrefDoc=hrefDocs[len(hrefDocs) -1]
lastArticleHref=lastArticleHrefDoc["href"].encode('UTF-8')
iflastArticleHref==None:
return []
print" > last page href:"+lastArticleHref
lastPageIndex=lastArticleHref.rfind("/")
lastPageNum=int(lastArticleHref[lastPageIndex+1:])
urlInfo="http://blog.csdn.net"+lastArticleHref[0:lastPageIndex]
pageUrlList= []
forxinxrange(1, lastPageNum+1):
pageUrl=urlInfo+"/"+str(x)
pageUrlList.append(pageUrl)
log(" > page "+str(x) +": "+pageUrl)
log("total pages: "+str(len(pageUrlList)) +"\n")
returnpageUrlList
defgetArticleList(url):
# 获取所有的文章的 url/title
pageUrlList=getPageUrlList(url)
articleListDocs= []
strPage=" > parsing page {0}"
pageNum=0
globalgRetryCount
forpageUrlinpageUrlList:
retryCount=0
pageNum=pageNum+1
pageNumStr=strPage.format(pageNum)
printpageNumStr
whileretryCount<=gRetryCount:
try:
retryCount=retryCount+1
time.sleep(1.0) #访问太快会不响应
request=urllib2.Request(pageUrl, None, header)
response=urllib2.urlopen(request)
data=response.read().decode('UTF-8')
#print data
soup=BeautifulSoup(data)
topArticleDocs=soup.find_all(id="article_toplist")
articleDocs=soup.find_all(id="article_list")
articleListDocs=articleListDocs+topArticleDocs+articleDocs
break
exceptException, e:
print"getArticleList exception:%s, url:%s, retry count:%d"% (e, pageUrl, retryCount)
pass
artices= []
topTile="[置顶]"
forarticleListDocinarticleListDocs:
linkDocs=articleListDoc.find_all("span", "link_title")
forlinkDocinlinkDocs:
#print linkDoc.prettify().encode('UTF-8')
link=linkDoc.a
url=link["href"].encode('UTF-8')
title=link.get_text().encode('UTF-8')
title=title.replace(topTile, '').strip()
oneHref="http://blog.csdn.net"+url
#log(" > title:" + title + ", url:" + oneHref)
artices.append([oneHref, title])
log("total articles: "+str(len(artices)) +"\n")
returnartices
defgetHtmlName(url):
htmlNameIndex=url.rfind("/");
urlLen=len(url)
htmlName=""
ifhtmlNameIndex+1==urlLen:
htmlNameIndex=url.rfind("/", 0, htmlNameIndex)
htmlName=url[htmlNameIndex+1:urlLen-1]
else:
htmlName=url[htmlNameIndex+1:]
returnhtmlName
defexportBlog(username, output):
url="http://blog.csdn.net/"+username
outputDir=output+"/"+username
log(" >> user name: "+username)
log(" >> output dir: "+outputDir)
log("start export...")
outputDir.replace("\\", "/")
ifnotos.path.exists(outputDir.decode("utf-8")):
os.makedirs(outputDir.decode("utf-8"))
articleList=getArticleList(url)
totalNum=len(articleList)
log("start downloading...")
currentNum=0
strPage="[{0}/{1}] ".decode("utf-8").encode("utf-8")
forarticleinarticleList:
currentNum=currentNum+1
strPageTemp=strPage.format(currentNum, totalNum)
strPageTemp=strPageTemp+article[1]
#log(strPageTemp)
download(article[0], username)
log("============================================================")
exportBlog(__username__, __output__)
#download(__testArticleUrl__, __output__)