利用Python制作一個MOOC公開課下載器

導語

記得很久以前寫過一些中國大學MOOC上的視頻下載器,不過好像都已經年久失修瞭。正好最近有需要,所以重新寫瞭一個,順便上來分享一波,寒假大傢也可以用它來下載點課程內卷一下:

廢話不多說,讓我們愉快地開始吧~

開發工具

Python版本:3.7.8

相關模塊:

DecryptLogin模塊;

tqdm模塊;

click模塊;

argparse模塊;

以及一些python自帶的模塊。

環境搭建

安裝Python並添加到環境變量,pip安裝需要的相關模塊即可。

先睹為快

運行方式:

python moocdl.py --url 課程鏈接

效果如下:

moocdl

隨便挑的一個課程測試的,結果是m3u8格式的,所以下載起來有點慢。默認會把所有的課件這些東西也一起下載下來放到對應的目錄。

原理簡介

首先,我們需要先模擬登錄中國大學MOOC,這樣才能下載對應的課程資料,這裡借助公眾號之前開源的DecryptLogin包就好啦:

'''登錄'''
def login(self, username, password):
    lg = login.Login()
    infos_return, session = lg.icourse163(username, password)
    return infos_return, session

接著,我們簡單講解一下如何下載對應課程裡的資料。首先,我們需要獲得課程相關的基本資料,隨便點開個課程主頁就可以發現直接在返回的頁面裡就有:

提取我們需要的課程信息的代碼實現如下:

# 從課程主頁面獲取信息
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'從課程主頁面獲取的信息如下:\n\t[課程名]: {course_name}, [課程ID]: {course_name}, [TID]: {term_id}')

接著利用這些信息來爬取對應的資源列表:

# 獲取資源列表
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'成功獲得資源列表, 數量為{len(resource_list)}')

最後根據資源類型解析下載即可:

# 下載對應資源
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'],
        })

ok,大功告成啦,寫的有點簡略,因為晚上還有點其他事。大傢可以自己在手機端抓包試試,很簡單的~

到此這篇關於利用Python制作一個MOOC公開課下載器的文章就介紹到這瞭,更多相關Python公開課下載器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: