当前位置:   article > 正文

Python爬虫--爬取哔哩哔哩(B站)短视频平台视频_爬取b站视频

爬取b站视频

目录

1、开发工具

2、第三方库

3、实现思路

4.单个爬取B站视频

5.批量爬取B站视频

6.查找所需数据

结尾    


1、开发工具

Python3.9

pycharm

requests

和其他python内置库

2、第三方库

安装第三方库

pip install requests

3、实现思路

1.用requests发送get请求,获得下载链接

2.将下载到B站视频和音频保存到本地

3.使用ffmpeg来合并视频和音频。

4.并保存到本地。

4.单个爬取B站视频
  1. import os
  2. import requests
  3. import json
  4. import re
  5. from bs4 import BeautifulSoup
  6. import subprocess
  7. from detail_video import video_bvid
  8. # video_bvid 是一个从外部得到的单个视频ID
  9. video_bvid = 'your-single-bvid'
  10. class BilibiliVideoAudio:
  11. def __init__(self, bvid):
  12. self.bvid = bvid
  13. self.headers = {
  14. "referer": "https://search.bilibili.com/all?keyword=%E4%B8%BB%E6%92%AD%E8%AF%B4%E8%81%94%E6%92%AD&from_source=webtop_search&spm_id_from=333.1007&search_source=5&page=4&o=90",
  15. "origin": "https://search.bilibili.com",
  16. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
  17. 'Accept-Encoding': 'gzip, deflate, br'
  18. }
  19. def get_video_audio(self):
  20. # 构造视频链接并发送请求获取页面内容
  21. url = f'https://www.bilibili.com/video/{self.bvid}/?spm_id_from=333.337.search-card.all.click&vd_source=14378ecd144bed421affe1fe0ddd8981'
  22. content = requests.get(url, headers=self.headers).content.decode('utf-8')
  23. soup = BeautifulSoup(content, 'html.parser')
  24. # 获取视频标题
  25. meta_tag = soup.head.find('meta', attrs={'name': 'title'})
  26. title = meta_tag['content']
  27. # 获取视频和音频链接
  28. pattern = r'window\.__playinfo__=({.*?})\s*</script>'
  29. json_data = re.findall(pattern, content)[0]
  30. data = json.loads(json_data)
  31. video_url = data['data']['dash']['video'][0]['base_url']
  32. audio_url = data['data']['dash']['audio'][0]['base_url']
  33. return {
  34. 'title': title,
  35. 'video_url': video_url,
  36. 'audio_url': audio_url
  37. }
  38. def download_video_audio(self, url, filename):
  39. # 对文件名进行清理,去除不合规字符
  40. filename = self.sanitize_filename(filename)
  41. try:
  42. # 发送请求下载视频或音频文件
  43. resp = requests.get(url, headers=self.headers).content
  44. download_path = os.path.join('D:\\video', filename) # 构造下载路径
  45. with open(download_path, mode='wb') as file:
  46. file.write(resp)
  47. print("{:*^30}".format(f"下载完成:{filename}"))
  48. except Exception as e:
  49. print(e)
  50. def sanitize_filename(self, filename):
  51. # 定义不合规字符的正则表达式
  52. invalid_chars_regex = r'[\"*<>?\\|/:,]'
  53. # 替换不合规字符为空格
  54. sanitized_filename = re.sub(invalid_chars_regex, ' ', filename)
  55. return sanitized_filename
  56. def merge_video_audio(self, video_path, audio_path, output_path):
  57. """
  58. 使用ffmpeg来合并视频和音频。
  59. """
  60. try:
  61. command = [
  62. 'ffmpeg',
  63. '-y', # 覆盖输出文件如果它已经存在
  64. '-i', video_path, # 输入视频路径
  65. '-i', audio_path, # 输入音频路径
  66. '-c', 'copy', # 复制原始数据,不进行转码
  67. output_path # 输出视频路径
  68. ]
  69. subprocess.run(command, check=True)
  70. print(f"视频和音频合并完成:{output_path}")
  71. except subprocess.CalledProcessError as e:
  72. print(f"合并失败: {e}")
  73. def main():
  74. try:
  75. # 只处理一个 bvid
  76. bilibili = BilibiliVideoAudio(video_bvid)
  77. video_audio_info = bilibili.get_video_audio()
  78. title = video_audio_info['title']
  79. video_url = video_audio_info['video_url']
  80. audio_url = video_audio_info['audio_url']
  81. processed_videos_path = 'D:\\processed_videos'
  82. if not os.path.exists(processed_videos_path):
  83. os.makedirs(processed_videos_path)
  84. video_filename = f"{title}.mp4"
  85. audio_filename = f"{title}.mp3"
  86. output_filename = f"{title} - combined.mp4"
  87. video_file_path = os.path.join('D:\\video', video_filename)
  88. audio_file_path = os.path.join('D:\\video', audio_filename)
  89. output_file_path = os.path.join(processed_videos_path, output_filename)
  90. bilibili.download_video_audio(video_url, video_filename) # 下载视频
  91. bilibili.download_video_audio(audio_url, audio_filename) # 下载音频
  92. bilibili.merge_video_audio(video_file_path, audio_file_path, output_file_path) # 合并视频和音频
  93. # Optional: Delete the separate files after merge
  94. # os.remove(video_file_path)
  95. # os.remove(audio_file_path)
  96. except Exception as ex:
  97. print(f"Failed to process video/audio for {video_bvid}: {ex}")
  98. main()

5.批量爬取B站视频
  1. # 批量爬取b站上的视频
  2. import os
  3. import requests
  4. import json
  5. import re
  6. from bs4 import BeautifulSoup
  7. import subprocess
  8. from detail_video import video_bvid
  9. class BilibiliVideoAudio:
  10. def __init__(self, bvid):
  11. self.bvid = bvid
  12. self.headers = {
  13. "referer": "https://search.bilibili.com/all?keyword=%E4%B8%BB%E6%92%AD%E8%AF%B4%E8%81%94%E6%92%AD&from_source=webtop_search&spm_id_from=333.1007&search_source=5&page=4&o=90",
  14. "origin": "https://search.bilibili.com",
  15. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
  16. 'Accept-Encoding': 'gzip, deflate, br'
  17. }
  18. def get_video_audio(self):
  19. # 构造视频链接并发送请求获取页面内容
  20. url = f'https://www.bilibili.com/video/{self.bvid}/?spm_id_from=333.337.search-card.all.click&vd_source=14378ecd144bed421affe1fe0ddd8981'
  21. content = requests.get(url, headers=self.headers).content.decode('utf-8')
  22. soup = BeautifulSoup(content, 'html.parser')
  23. # 获取视频标题
  24. meta_tag = soup.head.find('meta', attrs={'name': 'title'})
  25. title = meta_tag['content']
  26. # 获取视频和音频链接
  27. pattern = r'window\.__playinfo__=({.*?})\s*</script>'
  28. json_data = re.findall(pattern, content)[0]
  29. data = json.loads(json_data)
  30. video_url = data['data']['dash']['video'][0]['base_url']
  31. audio_url = data['data']['dash']['audio'][0]['base_url']
  32. return {
  33. 'title': title,
  34. 'video_url': video_url,
  35. 'audio_url': audio_url
  36. }
  37. def download_video_audio(self, url, filename):
  38. # 对文件名进行清理,去除不合规字符
  39. filename = self.sanitize_filename(filename)
  40. try:
  41. # 发送请求下载视频或音频文件
  42. resp = requests.get(url, headers=self.headers).content
  43. download_path = os.path.join('D:\\video', filename) # 构造下载路径
  44. with open(download_path, mode='wb') as file:
  45. file.write(resp)
  46. print("{:*^30}".format(f"下载完成:{filename}"))
  47. except Exception as e:
  48. print(e)
  49. def sanitize_filename(self, filename):
  50. # 定义不合规字符的正则表达式
  51. invalid_chars_regex = r'[\"*<>?\\|/:,]'
  52. # 替换不合规字符为空格
  53. sanitized_filename = re.sub(invalid_chars_regex, ' ', filename)
  54. return sanitized_filename
  55. def merge_video_audio(self, video_path, audio_path, output_path):
  56. """
  57. 使用ffmpeg来合并视频和音频。
  58. """
  59. try:
  60. command = [
  61. 'ffmpeg',
  62. '-y', # 覆盖输出文件如果它已经存在
  63. '-i', video_path, # 输入视频路径
  64. '-i', audio_path, # 输入音频路径
  65. '-c', 'copy', # 复制原始数据,不进行转码
  66. output_path # 输出视频路径
  67. ]
  68. subprocess.run(command, check=True)
  69. print(f"视频和音频合并完成:{output_path}")
  70. except subprocess.CalledProcessError as e:
  71. print(f"合并失败: {e}")
  72. def main():
  73. # 批量获取多个视频的bid
  74. bvids = [
  75. # 0 1 2 3
  76. "BV187411i7zw","BV1wi4y1E7E6","BV1Gz4y1X7vh","BV1Lh411d7Lw", # 1
  77. # 4 5 6 7
  78. "BV1mJ411D7QB","BV1Z5411w7Xb","BV1op4y167kS","BV1Mp4y1p7Ck", # 2
  79. # 8 9 10 11
  80. "BV1nJ41187Zy","BV1qb4y1Z7JK","BV1f5411379u","BV1kt4y1Q792", # 3
  81. # 12 13 14 15
  82. "BV1Qy4y1e7kk","BV1T7411T7q6","BV1k64y1k7QL","BV1J5411c7Rw", # 4
  83. # 16 17 18 19
  84. "BV1Db4y1y7yL","BV1cC4y1878T","BV11y4y1z7bY","BV1LJ411S7ML", # 5
  85. # 20 21 22 23
  86. "BV1X54y1L7mt","BV1S64y1D7HM","BV1rK4y1d7mZ","BV1b64y1y7AE", # 6
  87. # 24 25 26 27
  88. "BV1TK411F7MU","BV1HN411f7Em","BV1QA411x7KB","BV1pM4y1K7Ao", # 7
  89. # 28 29 30 31
  90. "BV1os4y1s7Aw","BV1sv411e71L","BV1xZ4y1A7gn","BV1E3411B7Q3", # 8
  91. # 32 33 34 35
  92. "BV1664y1d78D","BV1xv41177MR","BV13q4y1S7y1","BV1kJ411H7y8", # 9
  93. # 36 37 38 39
  94. "BV1Cq4y1Z7pM","BV1Jf4y147U7","BV1az4y117h4","BV1gy4y1h7wS", # 10
  95. ]
  96. for bvid in bvids:
  97. try:
  98. bilibili = BilibiliVideoAudio(bvid)
  99. video_audio_info = bilibili.get_video_audio()
  100. title = video_audio_info['title']
  101. video_url = video_audio_info['video_url']
  102. audio_url = video_audio_info['audio_url']
  103. bilibili.download_video_audio(video_url, f"{title}.mp4") # 下载视频
  104. bilibili.download_video_audio(audio_url, f"{title}.mp3") # 下载音频
  105. except Exception as ex:
  106. print(f"Failed to download video/audio for {bvid}: {ex}")
  107. processed_videos_path = 'D:\\processed_videos'
  108. if not os.path.exists(processed_videos_path):
  109. os.makedirs(processed_videos_path)
  110. # 注意:B站和其他短视频平台的视频不同,需要分别下载视频和音频,最后将视频和音频拼接到一块
  111. for bvid in bvids:
  112. try:
  113. bilibili = BilibiliVideoAudio(bvid)
  114. video_audio_info = bilibili.get_video_audio()
  115. title = video_audio_info['title']
  116. video_url = video_audio_info['video_url']
  117. audio_url = video_audio_info['audio_url']
  118. video_filename = f"{title}.mp4"
  119. audio_filename = f"{title}.mp3"
  120. output_filename = f"{title} - combined.mp4"
  121. video_file_path = os.path.join('D:\\video', video_filename)
  122. audio_file_path = os.path.join('D:\\video', audio_filename)
  123. output_file_path = os.path.join(processed_videos_path, output_filename)
  124. bilibili.download_video_audio(video_url, video_filename) # 下载视频
  125. bilibili.download_video_audio(audio_url, audio_filename) # 下载音频
  126. bilibili.merge_video_audio(video_file_path, audio_file_path, output_file_path) # 合并视频和音频
  127. # Optional: Delete the separate files after merge
  128. # os.remove(video_file_path)
  129. # os.remove(audio_file_path)
  130. except Exception as ex:
  131. print(f"Failed to process video/audio for {bvid}: {ex}")
  132. main()
6.查找所需数据

   1)bvid    

   2)referer / origin / User-Agent / Accept-Encoding

   

结尾    

希望大家喜欢我的分享!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/575666
推荐阅读
相关标签
  

闽ICP备14008679号