python 哔哩哔哩 bilibili视频下载

第一次写 代码直接复制就能用,需要改一下cookie,没有就删掉
这里简述一下:直接在bili的HTML文件里面就能找到
这里附加一个链接https://download.csdn.net/download/weixin_50994940/89614565
这个链接是ffmpeg软件,因为这里的代码调用了ffmpeg,将ffmpeg 放在py文件同目录下就行
这里需要下载两个库【requests】和lxml 
下载方法是:
1、按【win】和【R】这两个键,输入【cmd】,在打开的cmd窗口中输入:【pip install requests】 按回车键即【Enter】

2、按【win】和【R】这两个键,输入【cmd】,在打开的cmd窗口中输入:【pip install lxml】 按回车键即【Enter】

import os
from requests import get
from lxml import etree
from json import loads
from re import findall

def fo(shuzi,url1):
    bvid = set()
    if not os.path.exists("视频"):
        os.mkdir("视频")
    if not os.path.exists("视频2"):
        os.mkdir("视频2")
    fin=findall("\\?p=\\d{1,5}",url1)[0]
    print(f"fin:   {fin}")

    if len(findall("https.*?/\\?p.*",url1))<1:
        url1=url1.replace("?p","/?p")
    url1=url1.replace(fin,f"?p={shuzi}")
    print(url1)
    headers1 = {
        "Accept":"*/*",
        "Accept-Encoding":"gzip,deflate,br",
        "Connection":"keep-alive",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
        "cookie":"自己填没有就把这一行删掉",
        "Host": "www.bilibili.com",
        "Referer":"https://space.bilibili.com/2082563218/favlist?fid=2245416018&ftype=create"
    }
    headers = {
        "Cookie": "自己填没有就把这一行删掉",
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/547.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
        "HHost":"xy220x180x44x51xy.mcdn.bilivideo.cn:4483",
        "Accept-Encoding":"gzip,deflate, br",
        "Accept":"*/*",
        "Connection": "keep-alive",
        "sec-ch-ua": '"Chromium";v="112","Google Chrome";v="112","Not:A-Brand";v="99"',
        "Referer": f"{url1}",
        }

    headers2 = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "Cookie": "自己填没有就把这一行删掉",
        "DNT": "1",
        "Host": "www.bilibili.com",
        "Referer": "https://www.bilibili.com/?spm_id_from=333.788.0.0",
        "sec-ch-ua": "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 python"
    }
    html = get(url=url1, headers=headers1,verify=False)
    # html_fin=findall("<a href=.*?>.*?</a>",html.text)
    # print(html_fin)
    xx = etree.HTML(html.text)
    yua = xx.xpath('//head/title/text()')[0]
    yua = yua.replace('/', '')
    yua = yua.replace('\\', '')
    yua = yua.replace(':', '')
    yua = yua.replace('*', '')
    yua = yua.replace('?', '')
    yua = yua.replace('?', '')
    yua = yua.replace('"', '')
    yua = yua.replace('<', '')
    yua = yua.replace('>', '')
    yua = yua.replace(' ', '')
    yua = yua.replace('~', '')
    yua = yua.replace('^', '')
    yua = yua.replace('|', '')
    yua = yua.replace('&', '')
    name = yua.replace('|', '')
    print(name)

    repos = html.text
    # print(repos)
    res = findall('<script>window.__playinfo__=(.*?)</script>', repos)
    x = findall("\{.*\}", res[0])
    json_x = loads(x[0])
    print(json_x)
    # 视频
    video = json_x["data"]["dash"]['video']  
    print(f"video  {video}")
    video = video[0]  
    print(f"video  {video}")
    video_fin=findall('https.*?logo=8\d{1,10}',str(video))
    if len(video_fin)>=1:
        print(f"video_fin:{video_fin}")
        video=video_fin[-1]
        print(f"video_fin:{video}")
    else:
        video = video["backupUrl"][0]  
    # 音频
    audio = json_x["data"]["dash"]['audio']  
    print(f"audio   {audio}")
    audio = audio[0]  
    print(f"audio   {audio}")
    audio = audio["backupUrl"][0]  
    video_mp4=f"{name}.mp4"
    audio_mp3=f"{name}.mp3"
    print(f"video 下载地址:{video}")
    htmls = get(url=video, headers=headers,verify=False)
    with open(f"视频2\\{video_mp4}", 'ab') as kr:
        kr.write(htmls.content)
    htmld = get(url=audio, headers=headers,verify=False)
    with open(f"视频2\\{audio_mp3}", 'ab') as kr:
        kr.write(htmld.content)
    file = os.getcwd()
    output_path = f"{file}\\视频\\{shuzi}_{name}.mp4"
    video_clip = f"{file}\\视频2\\{name}.mp4"
    audio_clip = f"{file}\\视频2\\{name}.mp3"
    os.system(
        f"ffmpeg.exe -i {video_clip} -i {audio_clip} -c:v copy -c:a copy  {output_path}")
    # time.sleep(1)
    # os.remove(video_clip)
    # os.remove(audio_clip)
def fo1(url1):
    # url1=input("请输入url:")
    bvid = set()
    file = os.getcwd()

    if not os.path.exists(f"{file}\视频1"):
        os.mkdir(f"{file}\视频1")
    if not os.path.exists(f"{file}\视频2"):
        os.mkdir(f"{file}\视频2")
    

    
    headers1 = {
        "Accept":"*/*",
        "Accept-Encoding":"gzip,deflate,br",
        "Connection":"keep-alive",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
        "cookie":"自己填没有就把这一行删掉",
        "Host": "www.bilibili.com",
        "Referer":"https://space.bilibili.com/2082563218/favlist?fid=2245416018&ftype=create"
    }
    headers = {
        "Cookie": "自己填没有就把这一行删掉",
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/547.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
        "HHost":"xy220x180x44x51xy.mcdn.bilivideo.cn:4483",
        "Accept-Encoding":"gzip,deflate, br",
        "Accept":"*/*",
        "Connection": "keep-alive",
        "sec-ch-ua": '"Chromium";v="112","Google Chrome";v="112","Not:A-Brand";v="99"',
        "Referer": f"{url1}",
        }

    headers2 = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "Cookie": "自己填没有就把这一行删掉",
        "DNT": "1",
        "Host": "www.bilibili.com",
        "Referer": "https://www.bilibili.com/?spm_id_from=333.788.0.0",
        "sec-ch-ua": "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 python"
    }
    html = get(url=url1, headers=headers1,verify=False)
    # html_fin=findall("<a href=.*?>.*?</a>",html.text)
    # print(html_fin)
    xx = etree.HTML(html.text)
    yua = xx.xpath('//head/title/text()')[0]
    yua = yua.replace('/', '')
    yua = yua.replace('\\', '')
    yua = yua.replace(':', '')
    yua = yua.replace('*', '')
    yua = yua.replace('?', '')
    yua = yua.replace('?', '')
    yua = yua.replace('"', '')
    yua = yua.replace('<', '')
    yua = yua.replace('>', '')
    yua = yua.replace(' ', '')
    yua = yua.replace('~', '')
    yua = yua.replace('^', '')
    yua = yua.replace('|', '')
    yua = yua.replace('&', '')
    name = yua.replace('|', '')
    print(name)

    repos = html.text
    # print(repos)
    res = findall('<script>window.__playinfo__=(.*?)</script>', repos)
    x = findall("\{.*\}", res[0])
    json_x = loads(x[0])
    print(json_x)
    # 视频
    video = json_x["data"]["dash"]['video']  
    print(f"video  {video}")
    video = video[0]  
    print(f"video  {video}")
    video_fin=findall('https.*?logo=8\d{1,10}',str(video))
    if len(video_fin)>=1:
        print(f"video_fin:{video_fin}")
        video=video_fin[-1]
        print(f"video_fin:{video}")
    else:
        video = video["backupUrl"][0]  
    # 音频
    audio = json_x["data"]["dash"]['audio'] 
    print(f"audio   {audio}")
    audio = audio[0]  
    print(f"audio   {audio}")
    audio = audio["backupUrl"][0]  
    video_mp4=f"{name}.mp4"
    audio_mp3=f"{name}.mp3"
    print(f"video 下载地址:{video}")
    htmls = get(url=video, headers=headers,verify=False)
    with open(f"视频2\\{video_mp4}", 'ab') as kr:
        kr.write(htmls.content)
    htmld = get(url=audio, headers=headers,verify=False)
    with open(f"视频2\\{audio_mp3}", 'ab') as kr:
        kr.write(htmld.content)
        # r"D:\Users\A\PycharmProjects\pythonProject\程序目录3\bilibili"
    output_path = f"{file}\\视频1\\{name}.mp4"
    video_clip = f"{file}\\视频2\\{name}.mp4"
    audio_clip = f"{file}\\视频2\\{name}.mp3"
    os.system(
        f"ffmpeg.exe -i {video_clip} -i {audio_clip} -c:v copy -c:a copy  {output_path}")


while  True:
    url1 = input("请输入网址:")
    if url1.find('?p=') != -1:
        for shuzi in range(1, 30):
            fo(shuzi, url1)
    else:
        print("执行程序2")
        fo1(url1)
#-----------------------------------------------------------------------亮哥2024-07-01
  • 18
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值