斗魚視頻下載

思路

在文章的開頭,先分享一個(gè)名叫You-Get的視頻內(nèi)容嗅探器,是Python寫的,支持解析中外幾乎所有主流視頻網(wǎng)站的視頻,其中就包括斗魚視頻,關(guān)于斗魚視頻的解析可以在src/you_get/extractors/douyutv.py下的douyutv_video_download方法里找到。

但是,我一開始并不知道這個(gè)項(xiàng)目的存在。

以下是我的分析過程:

假設(shè)我要下載這個(gè)視頻,URL為https://v.douyu.com/show/XqeO74x3j8n7xywG。第一步肯定是抓包分析,有用的包一共有幾個(gè):

  • GET https://v.douyu.com/show/XqeO74x3j8n7xywG,這個(gè)頁面,也就是要抓取的URL本身會(huì)返回一個(gè)基本的HTML框架和js腳本。
  • common_94a55ff3a5.js, 這個(gè)腳本應(yīng)該包含了計(jì)算didsign的js方法。為什么說應(yīng)該?因?yàn)槲覜]找到,導(dǎo)致我第一種抓取思路中斷,才有了后來的用mobile端抓取的辦法,后面會(huì)細(xì)說。
  • POST ttps://v.douyu.com/api/swf/getStreamUrl,參數(shù)是 tt=1526513255&did=5474fae9365266a0746a7bf100051501&sign=b7721d3e3c0b90372a819eff12fa63ed&vid=XqeO74x3j8n7xywG。
    • 這里tt應(yīng)該是時(shí)間戳;vidvideo_id就是抓取URL里后面的一串字符;diddevice_id,這個(gè)我沒找到,但實(shí)現(xiàn)的方法很大概率在device_8cf6d524a4.js里;sign自然是某種簽名,可惜的是這個(gè)我壓根沒找到。
    • 這一條請(qǐng)求很重要,因?yàn)槿绻?qǐng)求成功,服務(wù)器會(huì)直接返回兩個(gè)URL,一個(gè)代表高清,一個(gè)代表普清。這兩個(gè)URL的返回內(nèi)容是視頻的地址列表playlist.m3u8。網(wǎng)站不會(huì)直接把整個(gè)視頻直接返回給你,而是會(huì)將視頻切割成若干個(gè)ts文件,而playlist.m3u8就是這些文件的列表。
    • 有了每個(gè)ts文件的地址,把它們都下載下來合并一下就是完整的視頻了。

然而現(xiàn)在卡在第三步,我不知道怎么獲取didsigndid還有點(diǎn)頭緒,sign是蹤跡全無。在我逐個(gè)排查每個(gè)請(qǐng)求的時(shí)候,我無意中看到了:"mobile_url":"https://vmobile.douyu.com/show/XqeO74x3j8n7xywG",位于第一條請(qǐng)求的返回內(nèi)容第9行末尾。

那么,移步mobile端,調(diào)整user-agent并重復(fù)上述過程:

  • GET https://vmobile.douyu.com/show/XqeO74x3j8n7xywG,這條和PC端上的返回內(nèi)容差不多,沒發(fā)現(xiàn)什么。
  • 之后,就是本項(xiàng)目最關(guān)鍵的一條報(bào)文GET https://vmobile.douyu.com/video/getInfo?vid=XqeO74x3j8n7xywG,這條報(bào)文直接返回了playlist.m3u8!再往后就和上面一樣了。

我嘗試了PC端的getInfo,不能成功 ,似乎只能在移動(dòng)端訪問。那么,現(xiàn)在的流程就是:

  1. 獲取視頻的vid(XqeO74x3j8n7xywG);
  2. 訪問https://vmobile.douyu.com/video/getInfo?vid=XqeO74x3j8n7xywG,獲取playlist.m3u8;
  3. 解析playlist.m3u8,提取所有ts文件的URL;
  4. 下載所有ts文件;
  5. 合并所有ts文件,輸出視頻。

因?yàn)檎也坏?code>sign和did,我去網(wǎng)上搜了搜,找到了文章開頭的You-Get,看了看它的源碼就是用移動(dòng)端做的,微微一笑。

代碼

合并ts文件

代碼唯一有點(diǎn)意思的地方是如何合并700多個(gè)ts文件,斗魚視頻最長(zhǎng)120分鐘,分成ts文件大概720個(gè)左右,直接用一行代碼肯定不行,windows的cmd有字符長(zhǎng)度限制。因此合并ts的邏輯要寫在代碼里。

其實(shí)合并的邏輯本質(zhì)就是數(shù)組求和,只不過順序不能打亂。我這里是用分治寫了個(gè)。

源代碼

import requests
import ast
import re
import os
import progressbar
from random import choice
import time

import configure as Configs

def get_playlist_m3u8(vid):
    url = "https://vmobile.douyu.com/video/getInfo?vid={0:s}".format(vid)

    header = {}
    header['user-agent'] = choice(Configs.FakeUserAgents_mobile)

    try:
        response = requests.get(url, headers=header)
        content = None
        if response.status_code == requests.codes.ok:
            content = response.text
            
    except Exception as e:
        print (e)

    djson = ast.literal_eval(content)

    if int(djson.get('error')) != 0:
        return None, None

    video_url = ast.literal_eval(content).get('data').get('video_url').replace('\\','')
    n = len('playlist.m3u8') * (-1)
    domain = video_url.split('?')[0][:n]
    print ("playlist.m3u8 file retrieved.")
    
    try:
        response = requests.get(video_url, headers=header)
        content = None
        if response.status_code == requests.codes.ok:
            content = response.text
            
    except Exception as e:
        print (e)

    return domain, content

def parser_m3u8(domain, fm3u8):
    fm3u8_list = fm3u8.split('\n')
    res = []

    for url in fm3u8_list:
        url = url.strip()
        if url and not url.startswith('#'):
            res.append(domain+url)

    return res

def download_ts(vid, tss):
    if not os.path.exists("Download"):
        os.makedirs("Download")

    header = {}
    header['user-agent'] = choice(Configs.FakeUserAgents)

    name_list = []
    print ("Parser {0:d} ts files in download list.".format(len(tss)))
    bar = progressbar.ProgressBar(max_value=len(tss), redirect_stdout=True)

    for i,ts in enumerate(tss):
        name = "{0:s}_{1:s}".format(vid, re.split('[_?]',ts)[2])
        name_list.append(name)
        content = ''
        try:
            response = requests.get(ts, headers=header)
            content = None
            if response.status_code == requests.codes.ok:
                content = response.content
            
        except Exception as e:
            print (e)

        with open("Download/"+name,'wb') as file:
            file.write(content)
        
        print ("Downloaded {0:s}".format(name))
        bar.update(i+1)

    return name_list

# 這里用了一個(gè)全局變量cnt,目的是讓每次合并的兩個(gè)文件從產(chǎn)生一個(gè)新的不重復(fù)的文件名
# 我本來打算用類似 name1 + name2 -> name2; delete name1 的操作
# 但是失敗了,這里先這樣寫,反正最后會(huì)中間文件都清掉,只剩最后一個(gè)結(jié)果
cnt = 0
def combine_ts(vid, name1, name2):
    global cnt
    os.system("cd Download & copy /b {0:s}+{1:s} temp{2:d}.ts".format(name1, name2, cnt))
    os.system("cd Download & del {0:s}".format(name1))
    os.system("cd Download & del {0:s}".format(name2))
    cnt += 1
    return ["temp{0:d}.ts".format(cnt-1)]
    
 
def combine(vid, ret):
    if len(ret) == 1:
        return ret
    
    if len(ret) == 2:
        return combine_ts(vid, ret[0], ret[1])

    return combine(vid, combine(vid, ret[:len(ret)//2])+combine(vid, ret[len(ret)//2:]))

if __name__ == '__main__':
    vid = '2V0JMVKrQXbWRY5k'
    domain, fm3u8 = get_playlist_m3u8(vid)
    tss = parser_m3u8(domain, fm3u8)
    ret = download_ts(vid, tss)
    lastname = combine(vid, ret)
    os.system("cd Download & rename {0:s} {1:s}.ts".format(lastname[0], vid))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容