-
Notifications
You must be signed in to change notification settings - Fork 42
/
SBB.py
186 lines (147 loc) · 6.81 KB
/
SBB.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '0.01'
__author__ = 'Julien G. (@bfishadow)'
'''
This script will download all artcles from a specific Sina Blog.
Based on these HTML files, you might generate an ebook by importing into Calibre, or use KindleGen by Amazon.
Or simply save them anywhere as archives.
'''
import sys, urllib2, urllib, os
from time import strftime
def getBetween(str, str1, str2):
strOutput = str[str.find(str1)+len(str1):str.find(str2)]
return strOutput
def extract_in(str, str1, str2):
begin = str.find(str1)+len(str1)
end = str.find(str2, begin)
strOutput = str[begin:end]
return strOutput, end
# getBetween = extract_in
def getImageMap(post_body):
res_list = []
# print post_body
tmp, i_end = extract_in(post_body, '<img src ="', '"')
print tmp
while tmp:
print tmp
res_list.append(tmp)
tmp, i_end = extract_in(post_body[i_end], "<img src =", '"')
return res_list
try:
os.mkdir("images")
except OSError:
pass
strUsage = "Usage: SBB.py <Sina blog URL> [asc]\n\nExample:\nSBB.py http://blog.sina.com.cn/gongmin desc\nSBB.py http://blog.sina.com.cn/u/1239657051\n"
#Step 0: get target blog homepage URL
try :
strUserInput = sys.argv[1]
except :
print strUsage
sys.exit(0)
try :
strUserOrder = sys.argv[2]
except :
strUserOrder = ""
#The URL *must* start with http://blog.sina.com.cn/, otherwise the universe will be destroied XD
if strUserInput.find("http://blog.sina.com.cn/") == -1 or len(strUserInput) <= 24 :
print strUsage
sys.exit(0)
#Get UID for the blog, UID is critical.
objResponse = urllib2.urlopen(strUserInput)
strResponse = objResponse.read()
objResponse.close()
strUID = getBetween(getBetween(strResponse, "format=html5;", "format=wml;"), "/blog/u/", '">')
if len(strUID) > 10 :
print strUsage
sys.exit(0)
#Here's the UID. Most of the UID is a string of ten digits.
strTargetUID = strUID
print strTargetUID
#Step 1: get list for first page and article count
strTargetBlogListURL = "http://blog.sina.com.cn/s/articlelist_" + strTargetUID + "_0_1.html"
objResponse = urllib2.urlopen(strTargetBlogListURL)
strResponse = objResponse.read()
objResponse.close()
strBlogPostList = getBetween(getBetween(strResponse,"$blogArticleSortArticleids","$blogArticleCategoryids"), " : [", "],")
strBlogPostID = strBlogPostList
strBlogPageCount = getBetween(getBetween(strResponse, "全部博文", "<!--第一列end-->"),"<em>(", ")</em>")
intBlogPostCount = int(strBlogPageCount) #article count
intPageCount = int(intBlogPostCount/50)+1 #page count, default page size is 50
strBlogName = getBetween(getBetween(strResponse, "<title>", "</title>"), "博文_", "_新浪博客")
#Step 2: get list for the rest of pages
for intCurrentPage in range(intPageCount - 1) :
strTargetBlogListURL = "http://blog.sina.com.cn/s/articlelist_" + strTargetUID + "_0_" + str(intCurrentPage + 2) + ".html"
objResponse = urllib2.urlopen(strTargetBlogListURL)
strResponse = objResponse.read()
strBlogPostList = getBetween(getBetween(strResponse,"$blogArticleSortArticleids","$blogArticleCategoryids"), " : [", "],")
strBlogPostID = strBlogPostID + "," + strBlogPostList
objResponse.close()
strBlogPostID = strBlogPostID.replace('"','')
#strBlogPostID <- this string has all article IDs for current blog
#Step 3: get all articles one by one
arrBlogPost = strBlogPostID.split(',')
if strUserOrder != "desc" :
arrBlogPost.reverse()
intCounter = 0
strHTML4Index = ""
for strCurrentBlogPostID in arrBlogPost :
intCounter = intCounter + 1
strTargetBlogPostURL = "http://blog.sina.com.cn/s/blog_" + strCurrentBlogPostID + ".html"
# strTargetBlogPostURL= "http://blog.sina.com.cn/s/blog_631d3a630102xaco.html"
if not strCurrentBlogPostID.strip():
print(strCurrentBlogPostID)
continue
objResponse = urllib2.urlopen(strTargetBlogPostURL)
strPageCode = objResponse.read()
objResponse.close()
#Parse blog title
strBlogPostTitle = getBetween(strPageCode, "<title>", "</title>")
strBlogPostTitle = strBlogPostTitle.replace("_新浪博客", "")
strBlogPostTitle = strBlogPostTitle.replace("_" + strBlogName, "")
#Parse blog post
strBlogPostBody = getBetween(strPageCode, "<!-- 正文开始 -->", "<!-- 正文结束 -->")
strBlogPostBody = strBlogPostBody.replace("http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif", "")
strBlogPostBody = strBlogPostBody.replace('src=""', "")
strBlogPostBody = strBlogPostBody.replace("real_src =", "src =")
if True:
png_urls = getImageMap(strBlogPostBody)
# print png_urls
if png_urls:
for idx, val in enumerate(png_urls):
if val.find("sinaimg.cn") < 0:
print "skip ", val
continue
else:
print "down ", val
png_name = "images/" + str(intCounter) + "_" + str(idx) + ".png"
strBlogPostBody = strBlogPostBody.replace(val, png_name)
urllib.urlretrieve(val, png_name)
else:
pass
#Parse blog timestamp
strBlogPostTime = getBetween(strPageCode, '<span class="time SG_txtc">(', ')</span>')
strBlogPostTime = strBlogPostTime[:]
#Write into local file
strHTML4Post = "<html>\n<head>\n<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />\n<title>" + strBlogPostTitle + "</title>\n<link href=""http://simg.sinajs.cn/blog7style/css/conf/blog/article.css"" type=""text/css"" rel=""stylesheet"" />\n</head>\n<body>\n<h2>" + strBlogPostTitle + "</h2>\n<p>By: <em>" + strBlogName + "</em> 原文发布于:<em>" + strBlogPostTime + "</em></p>\n" + strBlogPostBody + "\n<p><a href=""index.html"">返回目录</a></p>\n</body>\n</html>"
f_title = strBlogPostTitle
f_title = f_title.replace('\"', '')
f_title = f_title.replace('?', '')
f_title = f_title.replace('<', '')
f_title = f_title.replace('>', '')
f_title = f_title.replace(':', '')
f_title = f_title.replace('"', '')
f_title = f_title.replace('|', '')
f_title = f_title.replace('/', '')
strLocalFilename = "Post_" + str(intCounter) + "_" + strCurrentBlogPostID + "_" + f_title + ".html"
# print strLocalFilename
objFileArticle = open(strLocalFilename, "w")
objFileArticle.write(strHTML4Post);
objFileArticle.close
strHTML4Index = strHTML4Index + '<li><a href="' + strLocalFilename + '">' + strBlogPostTitle + '</a></li>\n'
print intCounter , "/", intBlogPostCount
strCurrentTimestamp = str(strftime("%Y-%m-%d %H:%M:%S"))
strHTML4Index = "<html>\n<head>\n<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />\n<title>" + strBlogName + "博客文章汇总</title>\n</head>\n<body>\n<h2>新浪博客:" + strBlogName + "</h2>\n<p>共" + str(intBlogPostCount) + "篇文章,最后更新:<em>" + strCurrentTimestamp + "</em></p>\n<ol>\n" + strHTML4Index + "\n</ol>\n</body>\n</html>"
objFileIndex = open("index.html", "w")
objFileIndex.write(strHTML4Index);
objFileIndex.close