DEV Community

loserrrrrrrrrrrc
loserrrrrrrrrrrc

Posted on Edited on

Scraping Bilibili Video Data Without Cookies

HTTP 412. That was the whole of Tuesday.

The response body was {"code": -412} and an empty result array. No captcha, no ban notice, no Retry-After header. The exact same request had worked forty minutes earlier. I spent the morning rotating user agents, adding Cookie: buvid3=... by hand, and reading forum posts about "B站反爬升级", all of which was wasted, because ten minutes after I stopped touching it the call went back to 200 on its own.

412 is a throttle. It is not a wall.

The version of this that actually cost a day

The local/cloud split is what makes it confusing. The same /x/web-interface/view URL answers 200 from my machine and 412 from the platform's cloud IP. I fired four attempts from the cloud with backoff and got exit_code 91 every time. Locally, first try, clean JSON.

So the failure is not "Bilibili blocked me". It is "Bilibili treats this IP range differently", and those need different fixes. Retry-and-sleep handles the first. Nothing handles the second except a fallback mode that does not need that endpoint.

The fallback is the hot board, which was reachable from the same cloud IP on the same run.

Keep the Referer header too. Drop it and the same request behaves like an unauthenticated browser tab — sometimes fine, sometimes empty, never with an explanation. Two headers, User-Agent and Referer, are the entire access model on this platform, and it is worth writing that down somewhere because a refactor will lose one of them and the symptom will look like a rate limit.

What you do not need

You do not need an account. A single GET to api.bilibili.com with a desktop Chrome UA and a Referer of bilibili.com returned 18 videos for the keyword python — titles, view counts, danmaku counts, like counts, durations, categories, uploader names, publish dates. No cookie jar, no login. That run was 2026-11-29 03:20 UTC.

import re
import time
import requests

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
API = "https://api.bilibili.com"

TAG = re.compile(r"<[^>]+>")

def clean(text):
    """Search results wrap matched keywords in <em class="keyword">."""
    return TAG.sub("", str(text or "")).strip()

def get(path, params, tries=3):
    s = requests.Session()
    s.headers.update({"User-Agent": UA, "Referer": "https://www.bilibili.com/",
                      "Accept": "application/json, text/plain, */*"})
    for attempt in range(tries):
        r = s.get(API + path, params=params, timeout=20)
        if r.status_code in (412, 429):
            # 412 is Bilibili's way of saying "slow down". It is not a ban.
            time.sleep(3 * (attempt + 1))
            continue
        payload = r.json()
        if payload.get("code") != 0:
            raise RuntimeError(f"code={payload.get('code')} msg={payload.get('message')}")
        return payload
    raise RuntimeError("gave up after retries")

def search(keyword, page=1):
    data = get("/x/web-interface/search/type",
               {"search_type": "video", "keyword": keyword, "page": page}).get("data") or {}
    out = []
    for v in data.get("result") or []:
        if v.get("type") != "video":
            continue
        out.append({
            "bvid": v.get("bvid"),
            "title": clean(v.get("title")),
            "author": clean(v.get("author")),
            "views": v.get("play"),
            "danmaku": v.get("video_review"),
            "likes": v.get("like"),
            "favorites": v.get("favorites"),
            "duration": v.get("duration"),      # "39:58:14", a string here
            "category": v.get("tname"),
            "published_ts": v.get("pubdate"),
            "url": f"https://www.bilibili.com/video/{v.get('bvid')}",
        })
    return out

rows = search("python")
print(len(rows), rows[0]["bvid"], rows[0]["views"])
# 18 BV1rpWjevEip 22118726
Enter fullscreen mode Exit fullscreen mode

Two details in there earn their keep.

clean() is not cosmetic. The search endpoint highlights whatever matched your keyword by wrapping it in <em class="keyword">. Skip the strip and your titles carry HTML tags, which then break every CSV export and every dashboard that renders them.

And duration is a string in this endpoint — "39:58:14" — while the same logical video returns an integer number of seconds from the view endpoint. Parse once, store seconds, format for display:

def to_seconds(value):
    if isinstance(value, str) and ":" in value:
        secs = 0
        for part in value.split(":"):
            secs = secs * 60 + int(part)
        return secs
    return int(value) if value is not None else None

def fmt(secs):
    return f"{secs // 3600:02d}:{secs % 3600 // 60:02d}:{secs % 60:02d}"
Enter fullscreen mode Exit fullscreen mode

That handles both shapes and gives you one sortable column.

Endpoint two: video detail

Search gives you a list view and nothing else. cid, coins and shares were null on all 18 search records in my run — the field is simply absent from the payload, and a naive pipeline writes null into a column your buyers expect to be populated.

The detail endpoint fills them in:

def video(bvid):
    data = get("/x/web-interface/view", {"bvid": bvid}).get("data") or {}
    stat = data.get("stat") or {}
    return {
        "bvid": data.get("bvid"),
        "cid": data.get("cid"),
        "title": clean(data.get("title")),
        "author": (data.get("owner") or {}).get("name"),
        "views": stat.get("view"),
        "danmaku": stat.get("danmaku"),
        "likes": stat.get("like"),
        "coins": stat.get("coin"),
        "favorites": stat.get("favorite"),
        "shares": stat.get("share"),
        "comments": stat.get("reply"),
        "duration_seconds": data.get("duration"),
        "published_at": data.get("pubdate"),
    }

print(video("BV1GJ411x7h7"))
Enter fullscreen mode Exit fullscreen mode

Real values from that call:

{
  "bvid": "BV1GJ411x7h7",
  "cid": 137649199,
  "title": "【官方 MV】Never Gonna Give You Up - Rick Astley",
  "author": "索尼音乐中国",
  "views": 109079191,
  "danmaku": 152684,
  "likes": 2991807,
  "coins": 1299992,
  "favorites": 1574649,
  "shares": 510825,
  "comments": 242415,
  "duration_seconds": 213,
  "published_at": "2019-12-31T23:43:23+00:00"
}
Enter fullscreen mode Exit fullscreen mode

109 million views on a 3-minute-33 video with 1.3 million coins. Coins are the Bilibili-specific signal — viewers spend a currency they can only earn by being an active user, which makes coins much harder to inflate than likes.

danmaku in that record is a number — 152,684 — but the bullets it counts are not in the payload at all. They live on a separate XML feed keyed on cid (137649199 for that video) and on the part number, one row per bullet: the text, the second it appears in the video, its colour, and whether it is a scrolling line, a bottom line or a pinned top line. The counter and the content are two different requests, and only the second one tells you what the audience was reacting to second by second. A count is a volume proxy; a timestamped row is behaviour.

The long tail is the interesting part

The 18 python rows ranged from 265 views to 35,738,131 views:

  • 35,738,131 views — BV1wD4y1o7AS, "花了2万多买的Python教程全套…", 24:41:01, uploader Python_子木
  • 22,118,726 views — BV1rpWjevEip, the "748 episodes" course, 39:58:14
  • 265 views — BV1vd1NzuEYA, uploaded 2026-11-28, 57:06:26

And the duration column is not a typo. BV1XDymzUEPS came back at 127:10:08 — 457,808 seconds. Chinese course uploads are often one giant playlist dumped into a single video object, so 100+ hour durations are normal. If your schema types duration as minutes in a 16-bit int, this dataset overflows it and the column wraps to nonsense.

When you ship it as a job

Two things in the Apify SDK 2.x cost me an evening each, and neither is Bilibili's fault.

Actor.get_input() is a coroutine now. Forget the await and the error is coroutine object has no attribute 'get', which reads like a typo somewhere else entirely. And Actor.charge() has to come after Actor.push_data() inside a try/except, or an unconfigured pricing block kills a run that already produced good data.

The SDK's own warning when pricing is not configured is worth recognising, because it is not an error:

[apify._charging] WARN  Ignored attempt to charge for an event
- the Actor does not use the pay-per-event pricing
Enter fullscreen mode Exit fullscreen mode

Your charge calls are firing. They are just being dropped.

What else this covers

The code above is search and video, two of seven modes. The full list is search, video, popular, ranking, comments, uploader, danmaku, and the three that answer the questions this article leaves open are:

  • Comments — every reply under a video: text, like_count, reply_count, parent_id ("0" on a top-level comment), is_sub_reply, published_at, and an author object that carries mid / name / level instead of the video-author shape. Pass bvids and it walks those threads; leave bvids empty and it takes the comments of whatever is on the hot board.
  • Uploader profiles — one row per mid: fans, following, likes (received across all of the uploader's videos), video_count, level, verified, official_title, vip_label, signature, space_url. 影视飓风 reads 19,215,895 fans over 956 videos in my pull; the founder's account, mid 2, is 1,440,908 fans over 45.
  • Danmaku — the bullets as rows: text, time_seconds (3 decimals), time_label, color as #RRGGBB, mode 1–9 with mode_label (scroll / bottom / top), font_size, danmaku_id, sent_at, and the video's pool_size.

All seven modes sit behind one input schema: Bilibili Scraper on Apify — search, video detail, popular, ranking, comments, uploader profiles and danmaku, 64 fields across the modes, no cookies. The 412 path still degrades to the hot board instead of failing the run, which is the fix I should have written on Tuesday morning instead of Tuesday evening.

All nine China data scrapers are at china-data-lab on Apify.

Next step: grab one bvid from search, call video() with it, and print both records side by side. Watch cid, coins and shares go from null to a number. After that you will never trust a list-only payload again.

Top comments (0)