forked from xiciliu/WanmenDownloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpiderWanmen.py
431 lines (381 loc) · 14.4 KB
/
SpiderWanmen.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
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 17:54:35 2018
@author: xici
"""
import requests
import re
import json,os,shutil
from hyper.contrib import HTTP20Adapter
thecookies={}
proxies = {
"http": "http://135.245.248.89:8000",
"https": "http://135.245.248.89:8000",
}
proxies=None
session=requests.Session()
#savein='course/'
savein='I:/Technology/AI/course/'
headers = {
"Accept": "text/html, application/xhtml+xml, */*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-GB",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Type":"application/json;charset=utf-8",
"DNT": "1",
#"Host": 'playback.wanmen.org',
#":authority": "api.wanmen.org",
#":method": "GET",
#":path": "/4.0/content/courses/5b74db50d3dd5f78a6289b7f",
#":scheme": "https",
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh-CN,zh;q=0.9",
"authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViY2Y0NWUxOWI1NWJiYTk0NTRjYWM2ZSIsImlhdCI6MTU0MDM5NTcwMCwiZXhwIjoxNTQyOTg3NzAwLCJpc3MiOiJ1cm46YXBpIn0.5rPwmkjnEKcKgd4VAA94aDrhWz-u19HlTnCFYuX8YMI",
"origin": "https://www.wanmen.org",
"referer": "https://www.wanmen.org/courses/5b74db50d3dd5f78a6289b7f",
"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
"x-app": "uni",
"x-time": "5bd092b6",
"x-token": "eeaf6ad6eef910ff2c7ae3c36806db1b"
}
def download(url,dir,name):
print("downloading with requests ",url)
#print(thecookies)
if len(name.split('.'))<=1:
space=url.split('.')
if len(space)>1:
prefix=space[len(space)-1]
name=name+'.'+prefix
print(dir+name)
if not os.path.exists(dir+name):
r = requests.get(url,cookies=thecookies,proxies=proxies)
with open(dir+name, "wb") as code:
code.write(r.content)
else:
print('skip down due to existance')
def saveM3u8(text,dir,name):
#处理/fragments/开头
text=removeFragment(text)
with open(dir+name, "w") as f:
f.write(text)
def removeFragment(text):
fra=re.findall('/fragments/(.*?)/',text)
if fra:
tempfrag=fra[0]
tempfrag='/fragments/'+tempfrag+'/'
text=text.replace(tempfrag,'')
return text
#返回.ts列表
def readts(content):
#return re.search(r'^(.*?)\((.*)\)$', _jsonp).group(2)
result=re.findall('(.*?)\.ts',content)
if result:
print('find ts: %d'%(len(result)))
return result
else:
print('not find ts')
#下载ts文件集合
def downts(tslist,dir,name,m3u8):
tsname=''
j=0
size=len(tslist)
for ts in tslist:
j=j+1
print('%d of %d'%(j,size))
tsname=ts.split('/')[-1]
#tsname=10000+j
if '/fragments/' in ts:
download('https://playback.wanmen.org'+ts+'.ts',dir,str(tsname)+'.ts')
else:
download('https://media.wanmen.org/'+ts+'.ts',dir,str(tsname)+'.ts')
#合并ts文件
combile(name,dir,m3u8)
#将当前目录下的.ts文件移动到dir目录
def movets(dir):
files=os.listdir('.')
for f in files:
if f.isfile() and os.path.splitext(path)[1]=='.ts':
shutil.move(f,dir)
def combile(name,dir,m3u8):
#移动所有.ts到对应的dir
#shutil.move(,dir)
exec_str=r'ffmpeg -allowed_extensions ALL -i '+dir+m3u8+' -c copy '+name
print(exec_str)
os.system(exec_str) # 使用cmd命令将资源整合
'''
exec_str = r'copy /b "' + r'*.ts" "'+ name
print(exec_str)
os.system(exec_str) # 使用cmd命令将资源整合
#exec_str = r'del "' + r'*.ts"'
#os.system(exec_str) # 删除原来的文件
'''
def del_file(path):
ls = os.listdir(path)
for i in ls:
c_path = os.path.join(path, i)
if os.path.isdir(c_path):
del_file(c_path)
else:
os.remove(c_path)
def readList(url):
r = requests.get(url,cookies=thecookies,proxies=proxies)
print(r.content)
def test():
str='''#EXTINF:8.341667,
a7e15b93-c3c1-4193-be6b-5dbed204b097_mobile_low0.ts
#EXTINF:3.169833,
a7e15b93-c3c1-4193-be6b-5dbed204b097_mobile_low1.ts
#EXTINF:8.341667,'''
result=re.findall('\n(.*?)\.ts',str)
print(result)
#login()
'''
print(thecookies)
S= requests.Session()#自动处理cookie
c=requests.cookies.RequestsCookieJar()
print(c)
c.set('o_cookie','760057995')
c.set('pgv_info','ssid=s7625432710')
c.set('pgv_pvi','3783237632')
c.set('pgv_pvid','8662440280')
c.set('pgv_si','s1062241280')
c.set('player_exist','1')
c.set('qqmusic_fromtag','66')
c.set('ts_last','y.qq.com/portal/player.html')
c.set('ts_refer','ADTAGbaiduald')
c.set('ts_uid','4584336768')
c.set('tvfe_boss_uuid','018abf599886d5ba')
c.set('yplayer_open','1')
c.set('yqq_stat','0')
c.set('yq_index','0')
S.cookies.update(c)
print(thecookies)
'''
#403
url='https://media.wanmen.org/94045fee-87bb-40a0-8f37-4b3438023908_pc_mid.m3u8?sign=f7b66bc9a7f20469764023a8474a4e68&t=5bc9f855&r=1f2f2223b901e816569902206ea4aec7'
url='https://playback.wanmen.org/recordings/z1.wanmen.44508051991983044/1536392266_1536393816.m3u8?sign=b544052be99f68b2ce77b454791e130b&t=5bd1ff04&r=7d8e3a18e1ac44538a6d5ab18828d2dc'
url='https://playback.wanmen.org/recordings/z1.wanmen.44508051991983044/1536370166_1536373477.m3u8?sign=75599270d4a812665e5196e2771c8d26&t=5bd31ba6&r=2a2608a7be5b3f9564aad2874cc4bda1'
url='https://playback.wanmen.org/recordings/z1.wanmen.44508051991983044/1536370166_1536373477.m3u8?sign=fe54c30a97bf899a58be2aba5b676769&t=5bd582ec&r=bb981fa55905ee11589e065811d3fcb6'
url='https://media.wanmen.org/a7e15b93-c3c1-4193-be6b-5dbed204b097_pc_high.m3u8?sign=5475bd976cf118c2b93c2a49e33d7539&t=5bd582a4&r=d6dd483afc95e2b541c98128e4472bbf'
res=requests.get(url,proxies=proxies)
if res.status_code==200:
print('get data')
#print(res)
#print(res.text)
m3u8=(url.split('?')[0]).split('/')[-1]
print(m3u8)
coursename='0909-强化学习入门(9)'
dir=savein+coursename+'/'
print('make dir: '+dir)
dir=dir.strip()
dirstr=dir
if dirstr[-1]=='/':
dirstr=dirstr[:-1]
print(dirstr)
if not os.path.exists(dirstr):
os.makedirs(dirstr)
print(res.text)
saveM3u8(res.text,dir,m3u8)
downts(readts(res.text),dir,savein+coursename+'.mp4',m3u8)
else:
print('get data error')
print(res)
#url='https://playback.wanmen.org/fragments/z1.wanmen.44508051991983044/1536392275604-1536392283937.ts'
#download(url,'','test.ts')
def login():
loginurl='https://api.wanmen.org/4.0/main/signin'
res=requests.post(loginurl,data={"account":"13651819457","password":"1234abcd","code":"","unionid":"","thirdtype":"","nickname":""},proxies=proxies)
#res=session.post(loginurl,data={"account":"13651819457","password":"1234abcd","code":"","unionid":"","thirdtype":"","nickname":""},proxies=proxies)
print(res.text)
thecookies = requests.utils.dict_from_cookiejar(res.cookies)
print(thecookies)
def readfromfile():
f=open('./587f469c196f0f565637213e.txt','r',encoding = 'utf-8')
str=f.read()
f.close()
if str.startswith(u'\ufeff'):
str = str.encode('utf8')[3:].decode('utf8')
return json.loads(str)
def down2(courseid,fromCache):
login()
js={}
if fromCache:
#加载已经下载到本地的json清单文件
js=readfromfile()
else:
#courseid='590c489571b2262ac78f1d75'
urlconfig='https://api.wanmen.org/4.0/content/courses/'+courseid
res = requests.get(urlconfig,cookies=thecookies,proxies=proxies)
#res.text
print(res.json())
js=res.json()
#ok, 下载课程说明和ppt课件
global savein
name=js['name']
savein=savein+name+'/'
if not fromCache:
with open(savein+courseid+'.txt', "w") as f:
f.write(res.text)
presentationVideo=js['presentationVideo']['hls']['pcHigh']
if os.path.exists(savein+name+'.mp4'):
print(name+'.mp4 already exists')
else:
res=requests.get(presentationVideo,headers=headers,cookies=thecookies,proxies=proxies)
url=presentationVideo
if res.status_code==200:
m3u8=(url.split('?')[0]).split('/')[-1]
print(m3u8)
dir=savein+name+'/'
print('make dir: '+dir)
dir=dir.strip()
dirstr=dir
if dirstr[-1]=='/':
dirstr=dirstr[:-1]
print(dirstr)
if not os.path.exists(dirstr):
os.makedirs(dirstr)
saveM3u8(res.text,dir,m3u8)
downts(readts(res.text),dir,savein+name+'.mp4',m3u8)
else:
print('get data error')
documents=js['documents']
if documents:
for doc in documents:
if os.path.exists(savein+doc['name']):
print(doc['name']+' already exists')
continue
else:
download(doc['url'],'',savein+doc['name'])
parentlecs=js['lectures']
index_p=0
for parentlec in parentlecs:
index_p=index_p+1
lecturename=str(index_p)+"_"+parentlec['name']
if not os.path.exists(savein+lecturename):
os.makedirs(savein+lecturename)
lectures=parentlec['children']
#print(js)
if lectures:
print(len(lectures))
index_v=0
for video in lectures:
print(video)
index_v=index_v+1
coursename=str(index_v)+"_"+video['name']
print('get data '+coursename)
if os.path.exists(savein+lecturename+'/'+coursename+'.mp4'):
print(coursename+'.mp4 is downloaded')
continue
url=video['hls']['pcHigh']
res=requests.get(url,headers=headers,cookies=thecookies,proxies=proxies)
if res.status_code==200:
m3u8=(url.split('?')[0]).split('/')[-1]
print(m3u8)
dir=savein+lecturename+'/'+coursename+'/'
print('make dir: '+dir)
dir=dir.strip()
dirstr=dir
if dirstr[-1]=='/':
dirstr=dirstr[:-1]
print(dirstr)
if not os.path.exists(dirstr):
os.makedirs(dirstr)
saveM3u8(res.text,dir,m3u8)
downts(readts(res.text),dir,savein+lecturename+'/'+coursename+'.mp4',m3u8)
else:
print('get data error')
print(res)
#break
#测试创建目录,即使有/结尾
def testCreateDir():
str='course/0908-强化学习入门(1)/'
str=str.strip()
if str[-1]=='/':
str=str[:-1]
print(str)
os.makedirs(str)
#ok
def testRemoveFragment():
file_object = open(r'course\0908-强化学习入门(1)\1536370166_1536373477.m3u8')
text=''
try:
text = file_object.read()
except e:
print(e)
finally:
file_object.close()
print(text)
text=removeFragment(text)
print(text)
#测试获取正确的课程清单,需要含hls
def testGetList():
courseid='5aaf651d77ae46495090ba57'
urlconfig='https://api.wanmen.org/4.0/content/courses/'+courseid
res = requests.get(urlconfig,cookies=thecookies,proxies=proxies)
#res.text
print(res.json())
#check
hls=res.json()['lectures'][0]['children'][0]['hls']
print(hls)
ok=False
if hls:
if len(hls)>0:
ok=True
else:
ok=False
else:
ok=False
if ok:
print('fine data')
else:
print('bad data')
#获取套餐课程
def getPackages():
login()
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cache-Control": "no-cache",
#"Connection": "keep-alive",
#"Content-Type":"application/json;charset=utf-8",
#"DNT": "1",
#"Host": 'playback.wanmen.org',
#":authority": "api.wanmen.org",
#":method": "GET",
#":path": "/4.0/me/packages",
#":scheme": "https",
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh-CN,zh;q=0.9",
"authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViY2Y0NWUxOWI1NWJiYTk0NTRjYWM2ZSIsImlhdCI6MTU0MDc4ODM4NCwiZXhwIjoxNTQzMzgwMzg0LCJpc3MiOiJ1cm46YXBpIn0.4j_TIj0Ugb7gQ9B6nX0HlA7V017iqV9lttNK03s1vTs", #同session下相同
"origin": "https://www.wanmen.org",
"referer": "https://www.wanmen.org/account/paid",
"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
"x-app": "uni",
"x-time": "5bd69264", #不同
"x-token": "432b7cbf9f177aac67a55d2afba81f5c" #不同
}
print(thecookies)
thecookies['Hm_lpvt_5b0b6201f68e4ffddfe9484b779c6fc4']='1540789713'
thecookies['Hm_lpvt_d3bc061b6a5d5d3715b5bed369a65ccb']='1540789713'
thecookies['UM_distinctid']='166be38d17818-0350e451a262d48-3a064d5a-100200-166be38d1790'
thecookies['_ga']='GA1.2.761715717.1540789713'
thecookies['_gid']='GA1.2.319287049.1540789713'
thecookies['Hm_lvt_5b0b6201f68e4ffddfe9484b779c6fc4']='1540384666,1540516330,1540789513'
thecookies['Hm_lvt_d3bc061b6a5d5d3715b5bed369a65ccb']='1540384666,1540516330,1540789514'
thecookies['thirdLogin']=''
thecookies['CNZZDATA1272834321']='222518564-1540787238-%7C1540787238' #222518564-1540787238-|1540787238
print(thecookies)
url='https://www.wanmen.org/account/paid'
res = requests.get(url,cookies=thecookies,headers=headers,proxies=proxies)
print(res.text)
#testCreateDir()
#test()
#testRemoveFragment()
#testGetList()
#getPackages()
savein='\\\\135.251.52.184\\Data\\Book\\ios开发3小时/'
down2('58d60011f0326f514e41e9d0',True)