本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
一、專案概述
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/157378.html
標籤:其他
