最近听了一个课程,视频只能在线看,播放声音很小,机智的我决定把视频抓下来。
首先在网页视频右键-审核元素-把m3u8的路径复制下来,然后路径放到下面的python执行(python3以上版本的),最后再用格式工厂把视频声音增大,视频大小限制(不要超过原视频大小),完美解决问题。如果代码改进可以运用到爬虫抓取。
python示例代码如下:# !/user/bin/env python
# -*- coding: utf-8 -*-
import os, shutil
import urllib.request, urllib.error, requests
# 打开并读取网页内容
def getUrlData(url):
try:
urlData = urllib.request.urlopen(url, timeout=20) # .read().decode('utf-8', 'ignore')
# urlData = requests.get(url, timeout=20) # .read().decode('utf-8', 'ignore')
return urlData
except Exception as err:
print('err getUrlData({url})\n'.format(url), err)
return -1
# 下载文件-requests
def getDown_reqursts(url, file_path):
try:
header = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"}
response = requests.get(url, timeout=120, headers=header)
with open(file_path, mode='ab+') as f:
f.write(response.content)
# 下载文件较大时,使用循环下载
print("down successful!")
except Exception as e:
print(e)
def getVideo_requests(url_m3u8, path, videoName):
urlData = getUrlData(url_m3u8)
tempName_video = os.path.join(path, '%s.ts'%videoName) # f'{}' 相当于'{}'.format() 或 '%s'%videoName
open(tempName_video, "wb").close() # 继续下载重复写入
# print(urlData)
for line in urlData:
url_ts = str(line.decode("utf-8")).strip() # 清除字符串前后存在的空格符和换行符
if not '.ts' in url_ts:
continue
else:
if not url_ts.startswith('http'): # 判断字符串是否以'http'开头,如果不是则说明url链接不完整,需要拼接
# 拼接ts流视频的url
url_ts = url_m3u8.replace(url_m3u8.split('/')[-1], url_ts)
print(url_ts)
getDown_reqursts(url=url_ts, file_path=tempName_video) # 下载视频流
filename = os.path.join(path, '%s.mp4'%videoName)
shutil.move(tempName_video, filename)
print('Great,%s.mp4 well down!'%videoName)
if __name__ == '__main__':
url_m3u8 = 'http://www.xxxx.com/video.m3u8' # 下载视频流地址
path = r'E:\123\'
videoName = url_m3u8.split('/')[-2]
getVideo_requests(url_m3u8, path, videoName)