当前位置:网站首页>没有对象的程序员如何过七夕
没有对象的程序员如何过七夕
2022-08-05 01:50:00 【Z_Xshan】
运行代码输入连接爬取视频 直接上代码
# encoding: utf-8
'''
爬取b站视频
'''
import requests
import json
import re
import os
class BilibiliVideoSpider(object):
def __init__(self, url, output_root=''):
self.url = url
if not os.path.isdir(output_root):
output_root = os.path.abspath(os.path.dirname(__file__))
self.output_root = output_root
self.headers = {
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
} # 定义请求头
def _match(self, text, pattern):
match = re.search(pattern, text)
if match is None:
print('this pattern was not matched !')
return json.loads(match.group(1))
def getHtml(self):
try:
response = requests.get(url=self.url, headers=self.headers) # 发请求,拿数据 (获取响应对象)
print(f'status_code: {response.status_code}')
if response.status_code == 200:
return response
except RequestException:
print('html reques error !')
def parseHtml(self, response):
playinfo = self._match(response.text, '__playinfo__=(.*?)</script><script>') # 视频详情json
initial_state = self._match(response.text, r'__INITIAL_STATE__=(.*?);\(function\(\)') # 视频内容json
video_url = playinfo['data']['dash']['video'][0]['baseUrl'] # 视频分多种格式,直接取分辨率最高的视频 1080p
audio_url = playinfo['data']['dash']['audio'][0]['baseUrl'] # 取音频地址
video_name = initial_state['videoData']['title'] # 取视频名字
return video_url, audio_url, video_name
def video_audio_merge(self, video_src, audio_src, video_dst):
'''使用ffmpeg单个视频音频合并'''
import subprocess
command = 'ffmpeg -i %s_video.mp4 -i %s_audio.mp4 -c copy %s.mp4 -y -loglevel quiet' % (
video_src, audio_src, video_dst)
subprocess.Popen(command, shell=True)
def downloadVideo(self, video_url, audio_url, video_name):
self.headers.update({"Referer": self.url})
print('开始下载视频: ')
video_content = requests.get(video_url, headers=self.headers)
audio_content = requests.get(audio_url, headers=self.headers)
print('%s视频大小:' % video_name, video_content.headers['content-length'])
print('%s音频大小:' % video_name, audio_content.headers['content-length'])
# 下载视频
received_video = 0
video = f'{self.output_root}/video.mp4'
with open(video, 'ab') as output:
while int(video_content.headers['content-length']) > received_video:
self.headers['Range'] = 'bytes=' + str(received_video) + '-'
response = requests.get(video_url, headers=self.headers)
output.write(response.content)
received_video += len(response.content)
# 下载音频开始
audio_content = requests.get(audio_url, headers=self.headers)
received_audio = 0
audio = f'{self.output_root}/audio.mp4'
with open(audio, 'ab') as output:
while int(audio_content.headers['content-length']) > received_audio:
self.headers['Range'] = 'bytes=' + str(received_audio) + '-'
response = requests.get(audio_url, headers=self.headers)
output.write(response.content)
received_audio += len(response.content)
print('视频下载完成')
video_dst = f'{self.output_root}/download.mp4'
self.video_audio_merge(video, audio, video_dst)
print(f'下载的视频: {video_dst}')
os.remove(video)
os.remove(audio)
def video_audio_merge(self, video_src, audio_src, video_dst):
'''使用ffmpeg单个视频音频合并'''
cmd = f'ffmpeg -y -i {audio_src} -i {video_src} -vcodec copy -acodec aac -strict -2 -q:v 1 {video_dst}'
print('execute cmd:', cmd)
os.system(cmd)
# subprocess.Popen(command, shell=True)
def run(self):
response = self.getHtml()
video_url, audio_url, video_name = self.parseHtml(response)
self.downloadVideo(video_url, audio_url, video_name)
def demo():
# url = 'https://www.bilibili.com/video/BV1Q5411p7bz?from=search&seid=14643382716113842219'
url=input('请输入视频地址:')
b = BilibiliVideoSpider(url)
b.run()
if __name__ == '__main__':
demo()
然后就保存到当前路径下的文件里了
边栏推荐
- 原生js实现多选框全部选中和取消效果
- CNI (Container Network Plugin)
- 蓝牙Mesh系统开发五 ble mesh设备增加与移除
- 10年测试经验,在35岁的生理年龄面前,一文不值
- iNFTnews | 对体育行业和球迷来说,NFT可以带来什么?
- Log an error encountered when compiling google gn "I could not find a ".gn" file ..."
- Lattice PCIe Learning 1
- Xunrui cms website cannot be displayed normally after relocation and server change
- 英特尔 XDC 2022 精彩回顾:共建开放生态,释放“基建”潜能
- VOC格式数据集转COCO格式数据集
猜你喜欢
使用OpenVINO实现飞桨版PGNet推理程序
迁移学习——Joint Geometrical and Statistical Alignment for Visual Domain Adaptation
LiveVideoStackCon 2022 Shanghai Station opens tomorrow!
释放技术创新引擎,英特尔携手生态合作伙伴推动智慧零售蓬勃发展
一文看懂推荐系统:召回06:双塔模型——模型结构、训练方法,召回模型是后期融合特征,排序模型是前期融合特征
Exploding the circle of friends, Alibaba produced billion-level concurrent design quick notes are too fragrant
Memory Forensics Series 1
Interview summary: Why do interviewers in large factories always ask about the underlying principles of Framework?
张驰咨询:揭晓六西格玛管理(6 Sigma)长盛不衰的秘密
为什么他们选择和AI恋爱?
随机推荐
Leetcode刷题——22. 括号生成
记录谷歌gn编译时碰到的一个错误“I could not find a “.gn“ file ...”
自定义线程池
PHP技能评测
1349. 参加考试的最大学生数 状态压缩
MySQL3
开篇-开启全新的.NET现代应用开发体验
亚马逊云科技 + 英特尔 + 中科创达为行业客户构建 AIoT 平台
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
The difference between a process in user mode and kernel mode [exclusive analysis]
ExcelPatternTool: Excel表格-数据库互导工具
Exercise: Selecting a Structure (1)
手把手基于YOLOv5定制实现FacePose之《YOLO结构解读、YOLO数据格式转换、YOLO过程修改》
Day Fourteen & Postman
pytorch的使用:卷积神经网络模块
EBS uses virtual columns and hint hints to optimize sql case
为什么他们选择和AI恋爱?
3. pcie.v file
Why is this problem reported when installing oracle11
内存取证系列1