当前位置: 首页 > Skill >

bilibili-video-search-and-download

bilibili-video-search-and-download

bilibili-video-search-and-download

使用yt-dlp和httpx搜索并下载B站(哔哩哔哩)视频,适用于按关键词搜索、获取视频信息、下载视频等需求。

1.0.0 2026.11.11 432
获取Skill文件查看使用说明
作 者:许辰 许可证: 更新时间:2026.11.11
本文目录展开

Bilibili Video Search

Use the bilibili-api-python library to search Bilibili videos by keyword and save results to search.json.

Environment Checks (Prerequisites)

Before running any search script, perform these checks:

1. Python availability

python3 --version

2. Virtual environment & dependencies

macOS may block system-wide pip install due to PEP 668. Always use a venv:

# Create venv if it doesn't exist
python3 -m venv /tmp/bilibili_venv

# Install dependencies (search)
/tmp/bilibili_venv/bin/pip install bilibili-api-python httpx

# Install dependencies (download)
/tmp/bilibili_venv/bin/pip install yt-dlp

# Fallback: if lxml download fails (common on slow networks), use douban mirror
/tmp/bilibili_venv/bin/pip install yt-dlp -i https://pypi.doubanio.com/simple/

Also ensure ffmpeg is installed (required for merging audio/video streams):

ffmpeg -version
# If not installed: brew install ffmpeg

3. Import check

Verify the library works:

/tmp/bilibili_venv/bin/python3 -c "import httpx; print('httpx OK')"

If bilibili_api is also available:

/tmp/bilibili_venv/bin/python3 -c "from bilibili_api import search; print('bilibili_api OK')"

4. Network check

Ensure Bilibili API is reachable:

curl -s -o /dev/null -w "%{http_code}" "https://api.bilibili.com/x/web-interface/search/type?search_type=video&keyword=test"

Expected: 200

Note: If bilibili-api-python is unavailable (e.g. lxml fails to download), fall back to calling the Bilibili REST API directly with httpx — see the example script below.

Core API

from bilibili_api import search

results = await search.search_by_type(
    keyword="关键词",
    search_type=search.SearchObjectType.VIDEO,
    page=1,
    page_size=20,
)

The response is a dict with a "result" key containing a list of video dicts.

Key Fields in Each Result

Field Description Example
bvid BV号 "BV1uv411q7Mv"
title 标题(含 <em> 高亮标签) "【黑神话】..."
author UP主名 "萌宠教主"
play 播放量 8838288
duration 时长(mm:ss 或秒) "2:51"
pic 封面图 URL "http://i2.hdslb.com/..."
pubdate 发布时间戳 1595203214

Sorting & Filtering

from bilibili_api.search import OrderVideo

await search.search_by_type(
    keyword="黑神话",
    search_type=search.SearchObjectType.VIDEO,
    order_type=OrderVideo.CLICK,       # 按播放量排序
    order_sort=0,                       # 0=降序, 1=升序
    time_range=7,                       # 7天内, -1=全部
    page=1,
    page_size=42,
)

OrderVideo options:

  • CLICK — 播放量
  • PUBDATE — 发布日期
  • DANMAKU — 弹幕数
  • STOW — 收藏数
  • SCORE — 评分

HTML Tags Cleanup

Bilibili titles contain <em class="keyword"> highlight tags. Strip them:

title = v.get("title", "").replace("<em class="keyword">", "").replace("</em>", "")

Save Results to JSON

Always save results to search.json with this structure:

{
  "keyword": "黑神话",
  "timestamp": "2026-05-27T23:31:55",
  "total": 20,
  "videos": [
    {
      "bvid": "BV1yup4ewEKz",
      "title": "【黑神话】...",
      "author": "萌宠教主",
      "play": 8838288,
      "duration": "2:51",
      "url": "https://www.bilibili.com/video/BV1yup4ewEKz"
    }
  ]
}

Video Download

Use yt-dlp to download Bilibili videos. The download_video.py script wraps yt-dlp with sensible defaults.

Usage

# By BV号
/tmp/bilibili_venv/bin/python3 scripts/download_video.py BV1qD4y1U7fs

# By full URL
/tmp/bilibili_venv/bin/python3 scripts/download_video.py https://www.bilibili.com/video/BV1qD4y1U7fs

Features

  • Downloads best available quality (auto-selects format)
  • Merges separate audio/video streams into single MP4 via ffmpeg
  • Embeds thumbnail and metadata into the output file
  • Files saved to downloads/ directory (relative to current working directory, i.e. the project root)
  • Post-download verification: checks file exists and is not empty

Important: The script must be run from the project root directory (where opencode.json is), not from the scripts/ folder itself. The downloads/ folder is created relative to the current working directory.

Troubleshooting & Known Issues

1. --print Implies --simulate (Download Does Not Actually Happen)

yt-dlp --print implies --simulate by default — it only prints the template result without downloading.

# ❌ 只计算文件名,不会下载
yt-dlp --print filename "URL"

# ✅ 下载完成后打印最终文件名
yt-dlp --print after_move:filename "URL"

Per yt-dlp docs: --print "Implies --quiet. Implies --simulate unless --no-simulate or later stages of WHEN are used." The download_video.py script uses --print after_move:filename which is a "later stage" and correctly triggers the download.

2. Always Verify Files After Download

The script output may claim a download succeeded when in fact the file was not created (e.g., if --print was used without after_move, or if yt-dlp encountered a silent error). Always verify:

  • The output file path exists on disk
  • The file size is greater than 0 bytes
  • (If using the script directly) Check ls -lh downloads/ after download

The download_video.py script now performs these checks automatically and exits with an error if the file is missing or empty.

3. Anthology Videos (合集)

Some Bilibili BV号 are anthologies (合集) containing multiple videos under one BV号. yt-dlp downloads the first video in the anthology by default:

[BiliBili] BV1mD4y1U7z9: Extracting videos in anthology
[BiliBili] BV1mD4y1U7z9: Downloading video formats for cid 348538681

If you need a different episode, use the specific URL with ?p=N parameter or the episode page URL directly.

4. Working Directory

The script creates downloads/ relative to the current working directory, not relative to the script location. Always run from the project root:

# ✅ 正确:在项目根目录运行
cd /path/to/project
/tmp/bilibili_venv/bin/python3 .opencode/skill/.../scripts/download_video.py BVxxxx

# ❌ 错误:会在 scripts/ 旁边创建 downloads/
cd .opencode/skill/.../scripts/
python3 download_video.py BVxxxx

5. Authentication for HD Quality

Without login, Bilibili limits downloads to 480P. For 1080P+/4K, pass browser cookies:

/tmp/bilibili_venv/bin/yt-dlp --cookies-from-browser chrome 
  -o "downloads/%(title)s.%(ext)s" 
  --merge-output-format mp4 
  "https://www.bilibili.com/video/BV1qD4y1U7fs"

6. Filename Handling

yt-dlp keeps Chinese characters and punctuation (【】《》~, etc.) in filenames as-is. This can cause shell globbing issues when using rm or other commands. Always quote file paths with double quotes.

Download Script

# scripts/download_video.py
import subprocess
import sys
from pathlib import Path

DOWNLOAD_DIR = Path("downloads")

def download_video(url: str, output_dir: Path):
    output_dir.mkdir(parents=True, exist_ok=True)
    print(f"正在下载: {url}")
    result = subprocess.run(
        [
            sys.executable, "-m", "yt_dlp",
            "-o", str(output_dir / "%(title)s.%(ext)s"),
            "--merge-output-format", "mp4",
            "--write-thumbnail",
            "--embed-thumbnail",
            "--embed-metadata",
            "--print", "after_move:filename",
            url,
        ],
        capture_output=True, text=True,
    )

    if result.returncode != 0:
        print(f"下载失败: {result.stderr.strip()}")
        sys.exit(1)

    out_path = result.stdout.strip()
    if not out_path:
        print("下载失败: 无法获取输出文件路径")
        sys.exit(1)

    out_file = Path(out_path)
    if not out_file.exists():
        print(f"下载失败: 文件不存在 — {out_path}")
        sys.exit(1)
    if out_file.stat().st_size == 0:
        print(f"下载失败: 文件为空 — {out_path}")
        sys.exit(1)

    print(f"下载完成: {out_path} ({out_file.stat().st_size / 1024 / 1024:.1f}MB)")

def main():
    if len(sys.argv) < 2:
        print("用法: python download_video.py <B站视频URL 或 BV号>")
        print("示例: python download_video.py https://www.bilibili.com/video/BV1qD4y1U7fs")
        print("示例: python download_video.py BV1qD4y1U7fs")
        sys.exit(1)

    arg = sys.argv[1]
    if arg.startswith("BV"):
        url = f"https://www.bilibili.com/video/{arg}"
    else:
        url = arg

    download_video(url, DOWNLOAD_DIR)

if __name__ == "__main__":
    main()

Complete Example Script

import asyncio
import json
from datetime import datetime
from bilibili_api import search


def clean_title(title: str) -> str:
    return title.replace("<em class="keyword">", "").replace("</em>", "")


async def search_videos(keyword: str, page: int = 1, page_size: int = 20):
    res = await search.search_by_type(
        keyword=keyword,
        search_type=search.SearchObjectType.VIDEO,
        page=page,
        page_size=page_size,
    )
    return res.get("result", [])


def save_results(keyword: str, results: list):
    data = {
        "keyword": keyword,
        "timestamp": datetime.now().isoformat(),
        "total": len(results),
        "videos": [
            {
                "bvid": v.get("bvid", ""),
                "title": clean_title(v.get("title", "")),
                "author": v.get("author", ""),
                "play": v.get("play", 0),
                "duration": v.get("duration", ""),
                "url": f"https://www.bilibili.com/video/{v.get('bvid', '')}",
            }
            for v in results
        ],
    }
    with open("search.json", "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f"结果已保存到 search.json ({len(results)} 条)")


async def main():
    keyword = input("请输入搜索关键词: ").strip()
    if not keyword:
        print("关键词不能为空")
        return
    results = await search_videos(keyword)
    if not results:
        print("未找到相关视频")
        return
    save_results(keyword, results)
    for i, v in enumerate(results, 1):
        title = clean_title(v.get("title", ""))
        print(f"{i:2d}. {title} — {v.get('author')} | 播放: {v.get('play')}")


if __name__ == "__main__":
    asyncio.run(main())

Dependencies

For search

python3 -m venv /tmp/bilibili_venv
/tmp/bilibili_venv/bin/pip install httpx

If bilibili-api-python is needed (optional):

/tmp/bilibili_venv/bin/pip install bilibili-api-python

For download

/tmp/bilibili_venv/bin/pip install yt-dlp
brew install ffmpeg          # for merging audio/video streams

If PyPI is slow, use a mirror:

/tmp/bilibili_venv/bin/pip install yt-dlp -i https://pypi.doubanio.com/simple/

Always run scripts with the venv Python:

/tmp/bilibili_venv/bin/python3 script.py

The library is fully async — always use asyncio.run() to execute.

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,036
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,020
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,016
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,014
Skill 文件
  • SKILL.md
    • Bilibili Video Search
    • Environment Checks (Prerequisites)
      • 1. Python availability
      • 2. Virtual environment & dependencies
      • 3. Import check
      • 4. Network check
    • Core API
    • Key Fields in Each Result
    • Sorting & Filtering
    • HTML Tags Cleanup
    • Save Results to JSON
    • Video Download
      • Usage
      • Features
    • Troubleshooting & Known Issues
      • 1. --print Implies --simulate (Download Does Not Actually Happen)
      • 2. Always Verify Files After Download
      • 3. Anthology Videos (合集)
      • 4. Working Directory
      • 5. Authentication for HD Quality
      • 6. Filename Handling
      • Download Script
    • Complete Example Script
    • Dependencies
      • For search
      • For download
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期