-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsaveLof.py
321 lines (277 loc) · 8.47 KB
/
saveLof.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
# -*- coding: UTF-8 -*-
import pandas as pd
from xml.etree import ElementTree as ET
import urllib.request
from datetime import datetime
import time
import os
import os.path
import requests
def makeDir(p):
try:
os.mkdir(p)
except OSError:
print(
"---***(T_T ) Creation of the directory %s failed or already existed***---" % p)
else:
print("---***(’v‘ ) Successfully created the directory %s ***----" % p)
def getType(item):
"""Helper to get the type of a post"""
thisType = item.find('type').text
return thisType
def getTerm(item, keyword, isTxt=True):
"""Find tags"""
try:
thisTerm = item.find(keyword)
if thisTerm == None:
thisTerm = 'N/A'
return thisTerm
if thisTerm == 'N/A':
return thisTerm
if isTxt:
return thisTerm.text
else:
return thisTerm
except AttributeError as e1:
thisTerm = 'N/A'
print(e1)
print("---***(QwQ ) Item Not Found***---")
if thisTerm == None:
thisTerm = 'N/A'
return thisTerm
if thisTerm == 'N/A':
return thisTerm
if isTxt:
return thisTerm.text
else:
return thisTerm
except TypeError as e2:
thisTerm = 'N/A'
print(e2)
print("---***(QwQ ) Item Not Found***---")
if thisTerm == None:
thisTerm = 'N/A'
return thisTerm
if thisTerm == 'N/A':
return thisTerm
if isTxt:
return thisTerm.text
else:
return thisTerm
def modifyText(txt):
if type(txt) != str:
return 'N/A'
else:
txt = txt.replace('<p>', '')
txt = txt.replace('</p>', '')
txt = txt.replace('<br />', '\n')
txt = txt.replace(' ', ' ')
txt = txt.replace('·', '·')
txt = txt.replace('"', '"')
txt = txt.replace('<a href=', '<')
txt = txt.replace('</a>', '')
txt = txt.replace('<li>', '')
txt = txt.replace('</li>', '')
return txt
def getContent(item):
thisCont = getTerm(item, 'content', True)
thisCont = modifyText(thisCont)
return thisCont
def getTitle(item):
thisTitle = getTerm(item, 'title')
return modifyText(thisTitle)
def getCaption(item):
thisCap = getTerm(item, 'caption', True)
return modifyText(thisCap)
def getTime(item):
ts = int(getTerm(item, 'publishTime', True))
tStamp = float(ts/1000)
tArray = time.localtime(tStamp)
DateTime = time.strftime("%Y-%m-%d %H:%M:%S", tArray)
return [ts, DateTime]
def getComments(item):
cmItem = getTerm(item, 'commentList', False)
comList = []
if cmItem != 'N/A':
com_lst = cmItem.findall('comment')
for cm in com_lst:
u_id = getTerm(cm, 'publisherNick', True)
u_cm = getContent(cm)
u_time = getTime(cm)
m = u_id + ': ' + u_cm + '(' + u_time[1] + ')'
comList.append(m)
return comList
def download(URL, path):
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) \
AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/35.0.1916.114 Safari/537.36',
'Cookie': 'AspxAutoDetectCookieSupport=1'}
reqst = urllib.request.Request(URL, headers={'User-Agent': 'Mozilla/5.0'})
try:
pic = urllib.request.urlopen(reqst)
print('downloading: ' + URL + '...')
path = os.path.abspath(path)
with open(path, 'wb') as localFile:
localFile.write(pic.read())
except Exception as e:
print(e)
def getPhotos(item, sendTime):
link_str = getTerm(item, 'photoLinks')
pic_num = link_str.count('"orign":"')
link_list = link_str.split('"orign":"')
link_list = link_list[1:]
suffix = '.jpg'
i = 1
output_links = []
output_names = []
for links in link_list:
if pic_num != 0:
pos2 = links.find('"')
url = links[: pos2]
name = 'Photo/' + str(sendTime) + '_#' + str(i) + suffix
download(url, name)
else:
url = 'N/A'
name = 'Photo/' + str(sendTime) + '_#' + str(i) + suffix
print('Name: ' + name)
print('URL: ' + url + '\n')
output_links.append(url)
output_names.append(name)
i += 1
return [output_names, output_links]
def getVideo(item, sendTime):
links = getTerm(item, 'embed')
suffix = '.mp4'
pos1 = links.find('"video_down_url":"')
if pos1 != -1:
chopped = links[pos1+18:]
pos2 = chopped.find('"')
url = chopped[:pos2]
else:
url = 'N/A'
name = 'Video/' + str(sendTime) + suffix
print('Name: ' + name)
print('URL: ' + url + '\n')
download(url, name)
return [name, url]
def getMusic(item):
all_info = getTerm(item, 'embed')
pos_mu_1 = all_info.find('"song_name":"')
if pos_mu_1 != -1:
chopped_1 = all_info[pos_mu_1+13:]
pos_mu_2 = chopped_1.find('"')
mu_name = chopped_1[:pos_mu_2]
else:
mu_name = 'N/A'
pos_url_1 = all_info.find('"listenUrl":"')
if pos_url_1 != -1:
chopped_2 = all_info[pos_url_1+13:]
pos_url_2 = chopped_2.find('"')
url = chopped_2[:pos_url_2]
else:
url = 'N/A'
return [mu_name, url]
Title = []
Date = []
Type = []
File = []
Link = []
Comments = []
Content = []
Tag = []
def addArchive(t, d, p, f, l, cm, cn, tag):
Title.append(t)
Date.append(d)
Type.append(p)
File.append(f)
Link.append(l)
Comments.append(cm)
Content.append(cn)
Tag.append(tag)
def grabMedia(item, tp):
title = getTitle(item)
time = getTime(item)
if tp == 'Video':
file, link = getVideo(item, time[0])
else:
file, link = getPhotos(item, time[0])
cm = getComments(item)
cn = getCaption(item)
tag = getTerm(item, 'tag')
addArchive(title, time[1], tp, file, link, cm, cn, tag)
def grabText(item, tp):
title = getTitle(item)
time = getTime(item)
ts = time[0]
cn = getContent(item)
file = 'Text/'+str(ts)+'.txt'
text_file = open(file, "w", encoding="utf-8")
n = text_file.write(cn)
text_file.close()
cm = getComments(item)
link = file
tag = getTerm(item, 'tag')
addArchive(title, time[1], tp, file, link, cm, cn, tag)
def grabMusic(item, tp):
title = getTitle(item)
time = getTime(item)
cn = getCaption(item)
file, link = getMusic(item)
cm = getComments(item)
tag = getTerm(item, 'tag')
addArchive(title, time[1], tp, file, link, cm, cn, tag)
def save_my_lofter(src, tree):
for p in ['Video', 'Photo', 'Text']:
try:
with open(os.path.abspath(p)) as f:
print("Directory " + p + ' Already Existed.')
except IOError:
print("Start creating Directory " + p + '...')
makeDir(p)
items = tree.findall('.//PostItem')
i = 1
for item in items:
tp = getType(item)
print('Start Processing Post No.' + str(i) + ' of type ' + tp + '...')
if tp == 'Video' or tp == 'Photo':
grabMedia(item, tp)
elif tp == 'Text':
grabText(item, tp)
else:
grabMusic(item, tp)
print('Finish Processing Post No.' + str(i) + '\n')
i += 1
data = {'标题': Title,
'日期': Date,
'类别': Type,
'文件名': File,
'文件链接': Link,
'评论': Comments,
'内容': Content,
'相关标签': Tag
}
pos1 = src.find('.xml')
chopped = src[:pos1]
info_name = chopped + '.csv'
info_pd = pd.DataFrame(data, columns=['标题',
'日期', '类别', '文件名', '文件链接',
'评论', '内容', '相关标签'])
info_pd.to_csv(info_name, encoding='utf_8_sig')
if __name__ == "__main__":
begin = False
found_tree = False
while not begin:
try:
src = input('请输入你的Lofter日志文件名称(含.xml后缀):')
if src == 'Q':
break
tree = ET.parse(src)
begin = True
found_tree = True
except:
print('请确认文件名称后再次输入,或输入Q退出。')
if found_tree:
try:
save_my_lofter(src, tree)
except:
print('运行错误,输出终止。请在GitHub留言。')