您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何用Python制作一個(gè)MOOC公開(kāi)課下載器”,在日常操作中,相信很多人在如何用Python制作一個(gè)MOOC公開(kāi)課下載器問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”如何用Python制作一個(gè)MOOC公開(kāi)課下載器”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
Python版本:3.7.8
相關(guān)模塊:
DecryptLogin模塊;
tqdm模塊;
click模塊;
argparse模塊;
以及一些python自帶的模塊。
安裝Python并添加到環(huán)境變量,pip安裝需要的相關(guān)模塊即可。
運(yùn)行方式:
python moocdl.py --url 課程鏈接
效果如下:
moocdl
隨便挑的一個(gè)課程測(cè)試的,結(jié)果是m3u8格式的,所以下載起來(lái)有點(diǎn)慢。默認(rèn)會(huì)把所有的課件這些東西也一起下載下來(lái)放到對(duì)應(yīng)的目錄。
首先,我們需要先模擬登錄中國(guó)大學(xué)MOOC,這樣才能下載對(duì)應(yīng)的課程資料,這里借助公眾號(hào)之前開(kāi)源的DecryptLogin包就好啦:
'''登錄''' def login(self, username, password): lg = login.Login() infos_return, session = lg.icourse163(username, password) return infos_return, session
接著,我們簡(jiǎn)單講解一下如何下載對(duì)應(yīng)課程里的資料。首先,我們需要獲得課程相關(guān)的基本資料,隨便點(diǎn)開(kāi)個(gè)課程主頁(yè)就可以發(fā)現(xiàn)直接在返回的頁(yè)面里就有:
提取我們需要的課程信息的代碼實(shí)現(xiàn)如下:
# 從課程主頁(yè)面獲取信息 url = url.replace('learn/', 'course/') response = self.session.get(url) term_id = re.findall(r'termId : "(\d+)"', response.text)[0] course_name = ' - '.join(re.findall(r'name:"(.+)"', response.text)) course_name = self.filterBadCharacter(course_name) course_id = re.findall(r'https?://www.icourse163.org/(course|learn)/\w+-(\d+)', url)[0] print(f'從課程主頁(yè)面獲取的信息如下:\n\t[課程名]: {course_name}, [課程ID]: {course_name}, [TID]: {term_id}')
接著利用這些信息來(lái)爬取對(duì)應(yīng)的資源列表:
# 獲取資源列表 resource_list = [] data = { 'tid': term_id, 'mob-token': self.infos_return['results']['mob-token'], } response = self.session.post('https://www.icourse163.org/mob/course/courseLearn/v1', data=data) course_info = response.json() file_types = [1, 3, 4] for chapter_num, chapter in enumerate(course_info.get('results', {}).get('termDto', {}).get('chapters', [])): for lesson_num, lesson in enumerate(chapter.get('lessons', [])) if chapter.get('lessons') is not None else []: for unit_num, unit in enumerate(lesson.get('units', [])): if unit['contentType'] not in file_types: continue savedir = course_name self.checkdir(savedir) for item in [self.filterBadCharacter(chapter['name']), self.filterBadCharacter(lesson['name']), self.filterBadCharacter(unit['name'])]: savedir = os.path.join(savedir, item) self.checkdir(savedir) if unit['contentType'] == file_types[0]: savename = self.filterBadCharacter(unit['name']) + '.mp4' resource_list.append({ 'savedir': savedir, 'savename': savename, 'type': 'video', 'contentId': unit['contentId'], 'id': unit['id'], }) elif unit['contentType'] == file_types[1]: savename = self.filterBadCharacter(unit['name']) + '.pdf' resource_list.append({ 'savedir': savedir, 'savename': savename, 'type': 'pdf', 'contentId': unit['contentId'], 'id': unit['id'], }) elif unit['contentType'] == file_types[2]: if unit.get('jsonContent'): json_content = eval(unit['jsonContent']) savename = self.filterBadCharacter(json_content['fileName']) resource_list.append({ 'savedir': savedir, 'savename': savename, 'type': 'rich_text', 'jsonContent': json_content, }) print(f'成功獲得資源列表, 數(shù)量為{len(resource_list)}')
最后根據(jù)資源類(lèi)型解析下載即可:
# 下載對(duì)應(yīng)資源 pbar = tqdm(resource_list) for resource in pbar: pbar.set_description(f'downloading {resource["savename"]}') # --下載視頻 if resource['type'] == 'video': data = { 'bizType': '1', 'mob-token': self.infos_return['results']['mob-token'], 'bizId': resource['id'], 'contentType': '1', } while True: response = self.session.post('https://www.icourse163.org/mob/j/v1/mobileResourceRpcBean.getResourceToken.rpc', data=data) if response.json()['results'] is not None: break time.sleep(0.5 + random.random()) signature = response.json()['results']['videoSignDto']['signature'] data = { 'enVersion': '1', 'clientType': '2', 'mob-token': self.infos_return['results']['mob-token'], 'signature': signature, 'videoId': resource['contentId'], } response = self.session.post('https://vod.study.163.com/mob/api/v1/vod/videoByNative', data=data) # ----下載視頻 videos = response.json()['results']['videoInfo']['videos'] resolutions, video_url = [3, 2, 1], None for resolution in resolutions: for video in videos: if video['quality'] == resolution: video_url = video["videoUrl"] break if video_url is not None: break if '.m3u8' in video_url: self.m3u8download({ 'download_url': video_url, 'savedir': resource['savedir'], 'savename': resource['savename'], }) else: self.defaultdownload({ 'download_url': video_url, 'savedir': resource['savedir'], 'savename': resource['savename'], }) # ----下載字幕 srt_info = response.json()['results']['videoInfo']['srtCaptions'] if srt_info: for srt_item in srt_info: srt_name = os.path.splitext(resource['savename'])[0] + '_' + srt_item['languageCode'] + '.srt' srt_url = srt_item['url'] response = self.session.get(srt_url) fp = open(os.path.join(resource['savedir'], srt_name), 'wb') fp.write(response.content) fp.close() # --下載PDF elif resource['type'] == 'pdf': data = { 't': '3', 'cid': resource['contentId'], 'unitId': resource['id'], 'mob-token': self.infos_return['results']['mob-token'], } response = self.session.post('http://www.icourse163.org/mob/course/learn/v1', data=data) pdf_url = response.json()['results']['learnInfo']['textOrigUrl'] self.defaultdownload({ 'download_url': pdf_url, 'savedir': resource['savedir'], 'savename': resource['savename'], }) # --下載富文本 elif resource['type'] == 'rich_text': download_url = 'http://www.icourse163.org/mob/course/attachment.htm?' + urlencode(resource['jsonContent']) self.defaultdownload({ 'download_url': download_url, 'savedir': resource['savedir'], 'savename': resource['savename'], })
到此,關(guān)于“如何用Python制作一個(gè)MOOC公開(kāi)課下載器”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。