1. 程式人生 > 實用技巧 >實現一鍵下載,批量快速爬取B站視訊

實現一鍵下載,批量快速爬取B站視訊

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理。

一、專案概述

1.專案背景

有一天,我突然想找點事做,想起一直想學但是沒有學的C語言,就決定來學一下。可是怎麼學呢?看書的話太無聊,報班學呢又快吃土了沒錢,不如去B站看看?果然,關鍵字C語言搜尋,出現了很多C語言的講課視訊:

B站https://www.bilibili.com/是一個很神奇的地方,簡直就是一個無所不有的寶庫,幾乎可以滿足你一切的需求和視覺欲。不管你是想看動畫、番劇 ,還是遊戲、鬼畜 ,亦或科技和各類教學視訊 ,只要你能想到的,基本上都可以在B站找到。對於程式猿或即將成為程式猿的人來說,B站上的程式設計學習資源是學不完的,可是B站沒有提供下載的功能,如果想儲存下載在需要的時候看,那就是一個麻煩了。我也遇到了這個問題,於是研究怎麼可以實現一鍵下載視訊,最終用Python這門神奇的語言實現了。

2.環境配置

這次專案不需要太多的環境配置,最主要的是有ffmpeg(一套可以用來記錄、轉換數字音訊、視訊,並能將其轉化為流的開源計算機程式)並設定環境變數就可以了。ffmpeg主要是用於將下載下來的視訊和音訊進行合併形成完整的視訊。

下載ffmpeg

可點選https://download.csdn.net/download/CUFEECR/12234789或進入官網http://ffmpeg.org/download.html進行下載,並解壓到你想儲存的目錄。

設定環境變數

  • 複製ffmpeg的bin路徑,如xxx\ffmpeg-20190921-ba24b24-win64-shared\bin
  • 此電腦右鍵點選屬性,進入控制面板\系統和安全\系統
  • 點選高階系統設定→進入系統屬性彈窗→點選環境變數→進入環境變數彈窗→選擇系統變數下的Path→點選編輯點選→進入編輯環境變數彈窗
  • 點選新建→貼上之前複製的bin路徑
  • 點選確定,逐步儲存退出 動態操作示例如下:

除了ffmpeg,還需要安裝pyinstaller庫用於程式打包。可用以下命令進行安裝:

pip install pyinstaller

如果遇到安裝失敗或下載速度較慢,可換源:

pip install pyinstaller -i https://pypi.doubanio.com/simple/

二、專案實施

1.匯入需要的庫

import json
import os
import
re import shutil import ssl import time import requests from concurrent.futures import ThreadPoolExecutor from lxml import etree

匯入的庫包括用於爬取和解析網頁的庫,還包括建立執行緒池的庫和進行其他處理的庫,大多數都是Python自帶的,如有未安裝的庫,可使用pip install xxx命令進行安裝。

2.設定請求引數

## 設定請求頭等引數,防止被反爬
headers = {
    'Accept': '*/*',
    'Accept-Language': 'en-US,en;q=0.5',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
}
params = {
    'from': 'search',
    'seid': '9698329271136034665'
}

設定請求頭等引數,減少被反爬的可能。

3.基本處理

def re_video_info(text, pattern):
    '''利用正則表示式匹配出視訊資訊並轉化成json'''
    match = re.search(pattern, text)
    return json.loads(match.group(1))


def create_folder(aid):
    '''建立資料夾'''
    if not os.path.exists(aid):
        os.mkdir(aid)


def remove_move_file(aid):
    '''刪除和移動檔案'''
    file_list = os.listdir('./')
    for file in file_list:
        ## 移除臨時檔案
        if file.endswith('_video.mp4'):
            os.remove(file)
            pass
        elif file.endswith('_audio.mp4'):
            os.remove(file)
            pass
        ## 儲存最終的視訊檔案
        elif file.endswith('.mp4'):
            if os.path.exists(aid + '/' + file):
                os.remove(aid + '/' + file)
            shutil.move(file, aid)

主要包括兩方面的基本處理,為正式爬取下載做準備:

  • 利用正則表示式提取資訊 通過requests庫請求得到請求後的網頁,屬於文字,通過正則表示式提取得到關於將要下載的視訊的有用資訊,便於後一步處理。
  • 檔案處理 將下載視訊完成後的相關檔案進行處理,包括刪除生成的臨時的音視訊分離的檔案和移動最終視訊檔案到指定資料夾。

4.下載視訊

def download_video_batch(referer_url, video_url, audio_url, video_name, index):
    '''批量下載系列視訊'''
    ## 更新請求頭
    headers.update({"Referer": referer_url})
    ## 獲取檔名
    short_name = video_name.split('/')[2]
    print("%d.\t視訊下載開始:%s" % (index, short_name))
    ## 下載並儲存視訊
    video_content = requests.get(video_url, headers=headers)
    print('%d.\t%s\t視訊大小:' % (index, short_name),
          round(int(video_content.headers.get('content-length', 0)) / 1024 / 1024, 2), '\tMB')
    received_video = 0
    with open('%s_video.mp4' % video_name, 'ab') as output:
        headers['Range'] = 'bytes=' + str(received_video) + '-'
        response = requests.get(video_url, headers=headers)
        output.write(response.content)
    ## 下載並儲存音訊
    audio_content = requests.get(audio_url, headers=headers)
    print('%d.\t%s\t音訊大小:' % (index, short_name),
          round(int(audio_content.headers.get('content-length', 0)) / 1024 / 1024, 2), '\tMB')
    received_audio = 0
    with open('%s_audio.mp4' % video_name, 'ab') as output:
        headers['Range'] = 'bytes=' + str(received_audio) + '-'
        response = requests.get(audio_url, headers=headers)
        output.write(response.content)
        received_audio += len(response.content)
    return video_name, index


def download_video_single(referer_url, video_url, audio_url, video_name):
    '''單個視訊下載'''
    ## 更新請求頭
    headers.update({"Referer": referer_url})
    print("視訊下載開始:%s" % video_name)
    ## 下載並儲存視訊
    video_content = requests.get(video_url, headers=headers)
    print('%s\t視訊大小:' % video_name, round(int(video_content.headers.get('content-length', 0)) / 1024 / 1024, 2), '\tMB')
    received_video = 0
    with open('%s_video.mp4' % video_name, 'ab') as output:
        headers['Range'] = 'bytes=' + str(received_video) + '-'
        response = requests.get(video_url, headers=headers)
        output.write(response.content)
    ## 下載並儲存音訊
    audio_content = requests.get(audio_url, headers=headers)
    print('%s\t音訊大小:' % video_name, round(int(audio_content.headers.get('content-length', 0)) / 1024 / 1024, 2), '\tMB')
    received_audio = 0
    with open('%s_audio.mp4' % video_name, 'ab') as output:
        headers['Range'] = 'bytes=' + str(received_audio) + '-'
        response = requests.get(audio_url, headers=headers)
        output.write(response.content)
        received_audio += len(response.content)
    print("視訊下載結束:%s" % video_name)
    video_audio_merge_single(video_name)

這部分包括系列視訊的批量下載和單個視訊的下載,兩者的大體實現原理近似,但是由於兩個函式的引數有差別,因此分別實現。在具體的實現中,首先更新請求頭,請求視訊連結並儲存視訊(無聲音),再請求音訊連結並儲存音訊,在這個過程中得到相應的視訊和音訊檔案的大小。

5.視訊和音訊合併成完整的視訊

def video_audio_merge_batch(result):
    '''使用ffmpeg批量視訊音訊合併'''
    video_name = result.result()[0]
    index = result.result()[1]
    import subprocess
    video_final = video_name.replace('video', 'video_final')
    command = 'ffmpeg -i "%s_video.mp4" -i "%s_audio.mp4" -c copy "%s.mp4" -y -loglevel quiet' % (
        video_name, video_name, video_final)
    subprocess.Popen(command, shell=True)
    print("%d.\t視訊下載結束:%s" % (index, video_name.split('/')[2]))


def video_audio_merge_single(video_name):
    '''使用ffmpeg單個視訊音訊合併'''
    print("視訊合成開始:%s" % video_name)
    import subprocess
    command = 'ffmpeg -i "%s_video.mp4" -i "%s_audio.mp4" -c copy "%s.mp4" -y -loglevel quiet' % (
        video_name, video_name, video_name)
    subprocess.Popen(command, shell=True)
    print("視訊合成結束:%s" % video_name)

這個過程也是批量和單個分開,大致原理差不多,都是呼叫subprogress模組生成子程序,Popen類來執行shell命令,由於已經將ffmpeg加入環境變數,所以shell命令可以直接呼叫ffmpeg來合併音視訊。

三、專案分析和說明

1.結果測試

對3種方式進行測試的效果如下:


作者:Corley

源自:快學python

轉載地址

https://blog.csdn.net/fei347795790?t=1