-
Notifications
You must be signed in to change notification settings - Fork 0
/
renrenAlbumDownloader.py
464 lines (416 loc) · 12.6 KB
/
renrenAlbumDownloader.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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#!/usr/bin/env python
# coding=<utf-8>
import urllib2, urllib
from HTMLParser import HTMLParser
from cookielib import CookieJar
import sys
import time
import os
import re
import json
username=""
password=""
UA="Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"
Cookie = ""
cj = CookieJar()
opener = None
regEx = "\\(第\d+/\d+张\\)"
fDebug = False
configFileName = 'configs.json'
# class MyHTMLParser(HTMLParser):
# def handle_starttag(self, tag, attrs):
# print "Encountered a start tag:", tag
# def handle_endtag(self, tag):
# print "Encountered an end tag :", tag
# def handle_data(self, data):
# print "Encountered some data :", data
class albumItem():
def __init__(self, albumName, albumHref):
self.Name = albumName
self.trimName()
self.Href = albumHref
self.dirPath = ""
self.opener = None
def trimName(self):
index = len(self.Name) - 1
while index >= 0:
if self.Name[index] == '(':
break
pass
index -= 1
pass
if index > 0:
self.Name = self.Name[:index]
pass
def createDir(self):
self.dirPath = os.path.abspath('./' + self.Name)
if not os.path.exists(self.dirPath):
os.mkdir(self.dirPath)
pass
def getFirstURL(self):
req = urllib2.Request(self.Href)
req.add_header("User-Agent", UA)
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
ret = opener.open(req)
pageS = ret.read()
ret.close()
divIndex = pageS.find('<div class="list')
divList = pageS[divIndex:]
pParser = photoListParser()
pParser.feed(divList)
return pParser.href
def saveLinktoDisk(self, urlLink, fileName):
print("Saving " + fileName)
req = urllib2.Request(urlLink)
req.add_header("User-Agent", UA)
ret = self.opener.open(req)
time.sleep(1)
lcFile = open(self.dirPath + "/" + fileName, "wb")
lcFile.write(ret.read())
lcFile.close()
ret.close()
def saveToDisk(self):
self.createDir()
firstPhotoLink = self.getFirstURL()
if fDebug:
print("Link to First Photo: " + firstPhotoLink)
pass
# try:
# input("Press Enter to continue")
# except:
# #Do nothing
# pass
nextPage = firstPhotoLink
while len(nextPage) != 0:
req = urllib2.Request(nextPage)
req.add_header("User-Agent", UA)
ret = self.opener.open(req)
pageS = ret.read()
ret.close()
p = re.compile(regEx)
b = p.search(pageS)
curNum = ""
totalNum = ""
tempNum = ""
if b == None:
#Album empty or only have 1 photo
curNum = "1"
totalNum = "1"
else:
match = b.group()
#Album has multiple photos
for index in range(len(match)):
curChar = match[index]
if curChar >= '0' and curChar <= '9':
tempNum += curChar
if curChar == '/':
curNum = tempNum
tempNum = ""
totalNum = tempNum
fileName = curNum + '.jpg'
hrefP = hrefParser()
hrefP.feed(pageS)
if '下载' not in hrefP.dict:
print("Warning: Album " + self.Name + " is empty!")
return
downloadLink = hrefP.dict['下载']
if curNum == totalNum:
nextPage = ""
else:
if '下一张' not in hrefP.dict:
return
nextPage = hrefP.dict['下一张']
if fDebug:
print("Current Num: ", curNum)
print("Total Num: ",totalNum )
# try:
# input("Press Enter to continue")
# except:
# pass
self.saveLinktoDisk(downloadLink, fileName)
pass
pass
def __str__(self):
curLine = "{0} : {1}".format(self.Name, self.Href)
return curLine
class photoListParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.stack=[]
self.albumList = []
self.do = True
self.stackAttrs=[]
self.href = ""
pass
def handle_starttag(self, tag, attrs):
if (self.do):
self.stack.append(tag)
self.stackAttrs.append((tag, attrs))
if tag == 'img' and 'td' in self.stack:
attrsD = {}
(curTag, curAttrs) = self.stackAttrs[-2]
for (name, value) in curAttrs:
attrsD[name] = value
pass
if curTag == 'a':
self.href = attrsD['href']
self.do = False
pass
pass
pass
def handle_data(self, data):
pass
def handle_endtag(self, tag):
if not self.do:
return
if len(self.stack) == 0:
self.do = False
return
curTag = self.stack.pop()
(curTag, curAttrs) = self.stackAttrs.pop()
if (curTag != tag) and fDebug:
print("ERROR Stack not balanced ", curTag, tag)
if (len(self.stack) == 0):
self.do = False
pass
class albumListParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.stack=[]
self.albumList = []
self.do = True
self.stackAttrs=[]
self.nextPage=""
pass
def handle_starttag(self, tag, attrs):
if (self.do):
self.stack.append(tag)
self.stackAttrs.append((tag, attrs))
if tag == 'a' and 'td' not in self.stack:
attrsD = {}
for (name, value) in attrs:
attrsD[name] = value
pass
if 'title' in attrsD and attrsD['title'] == '下一页':
self.nextPage = attrsD['href']
pass
pass
pass
pass
def handle_data(self, data):
if (not self.do):
return
curTag = self.stack[-1]
if curTag == 'a' and 'td' in self.stack:
#HREF
(curTag, curAttrs) = self.stackAttrs[-1]
attrsD = {}
for (name, value) in curAttrs:
attrsD[name] = value
pass
abHref = attrsD['href']
abName = data
abItem = albumItem(abName, abHref)
self.albumList.append(abItem)
pass
def handle_endtag(self, tag):
if not self.do:
return
if len(self.stack) == 0:
self.do = False
return
curTag = self.stack.pop()
(curTag, curAttrs) = self.stackAttrs.pop()
if (curTag != tag and fDebug):
print("ERROR Stack not balanced ", curTag, tag)
if (len(self.stack) == 0):
self.do = False
pass
class hrefParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.dict = {}
self.stack = []
self.tempHref = ""
def handle_starttag(self, tag, attrs):
self.stack.append(tag)
attrsD = {}
if tag == 'a':
for (name, value) in attrs:
attrsD[name] = value
pass
if 'href' in attrsD:
self.tempHref = attrsD['href']
pass
def handle_data(self, data):
curTag = self.stack[-1]
if (curTag == 'a'):
self.dict[data] = self.tempHref
pass
def handle_endtag(self, tag):
topTag = ""
if len(self.stack) != 0:
topTag = self.stack.pop()
if (topTag != tag and fDebug):
print("ERROR: Stack not balanced ", topTag, tag)
pass
class formParser(HTMLParser):
def handle_starttag(self, tag, attrs):
self.stack.append(tag)
#print(attrs)
attrsD = {}
for (name, value) in attrs:
attrsD[name] = value
#print(attrsD)
if 'name' in attrsD and tag == 'input':
curName = attrsD['name']
#print(curName)
curVal = ""
if ('value' in attrsD):
curVal = attrsD['value']
#print(curVal)
self.dict[curName] = curVal
if tag == 'form':
if ('action' in attrsD):
self.post = attrsD['action']
pass
def handle_endtag(self, tag):
topTag = self.stack.pop()
if (topTag != tag and fDebug):
print("ERROR: Stack not balanced ", topTag, tag)
pass
def handle_data(self, data):
#print(data)
pass
def __init__(self):
#super(formParser, self).__init__()
HTMLParser.__init__(self)
self.dict = {}
self.stack = []
self.post=""
pass
def accessHomePage():
global Cookie
global opener
hpUrl = "http://3g.renren.com/"
req = urllib2.Request(hpUrl)
req.add_header("User-Agent", UA)
time.sleep(5)
ret = urllib2.urlopen(req)
pageS = ret.read()
pageInfo = ret.info()
formIndexb = pageS.find('<form')
formIndexe = pageS.find('/form>')
formS = pageS[formIndexb:formIndexe+6]
ret.close()
formP = formParser();
formP.feed(formS)
formP.dict['email'] = username
formP.dict['password'] = password
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
data = urllib.urlencode(formP.dict)
reqLogin = urllib2.Request(formP.post, data)
reqLogin.add_header("User-Agent", UA)
time.sleep(5)
ret = opener.open(reqLogin)
pageS = ret.read()
ret.close()
hParse = hrefParser()
hParse.feed(pageS)
#print(hParse.dict)
if "个人主页" in hParse.dict:
return (hParse.dict['个人主页'])
def accessAlbum(hpLink):
global opener
req = urllib2.Request(hpLink)
req.add_header("User-Agent", UA)
time.sleep(5)
ret = opener.open(req)
pageS = ret.read()
#print(pageS)
hParser = hrefParser()
hParser.feed(pageS)
abLink = ""
if '相册' in hParser.dict:
abLink = hParser.dict['相册']
ret.close()
if abLink == "":
print("ERROR: Album link is empty")
sys.exit(0)
nextLink = abLink
albumItemList = []
print("Acquiring album list")
while len(nextLink) != 0 :
if fDebug:
print("Accessing", nextLink)
req = urllib2.Request(nextLink)
req.add_header("User-Agent", UA)
time.sleep(2)
ret = opener.open(req)
pageS = ret.read();
ret.close()
#print(pageS)
listIndex = pageS.find('<div class="list"')
albumDiv = ""
if (listIndex != 0):
albumDiv = pageS[listIndex:]
#print(albumDiv)
abParser = albumListParser()
abParser.feed(albumDiv)
albumItemList.extend(abParser.albumList)
nextLink = abParser.nextPage
pass
print("Available Albums: ")
for item in albumItemList:
print(item.Name)
pass
for item in albumItemList:
print("Accessing album " + item.Name)
item.saveToDisk()
pass
pass
def loadConfigs():
global username
global password
try:
inFile = open(configFileName, 'r')
except:
print("ERROR: configs.json failed to open.")
sys.exit(-1)
jsonData = json.load(inFile)
for key in jsonData:
if key == 'username':
username = jsonData[key]
if key == 'password':
password = jsonData[key]
inFile.close()
# if fDebug:
# print("User Name: ", username)
# print("Password: ", password)
def main():
global configFileName
global fDebug
params = sys.argv
if len(params) > 1:
for index in range(1, len(params)):
curParam = params[index]
if curParam[0] != '-':
continue
for cIndex in range(1, len(curParam)):
curChar = curParam[cIndex]
if curChar == 'd':
fDebug = True
pass
if curChar == 'a':
configFileName = 'configsD.json'
pass
pass
pass
pass
loadConfigs()
print("Do Login")
hpLink = accessHomePage()
accessAlbum(hpLink)
pass
if __name__ == '__main__':
main()