Bilibili 哔哩哔哩 Scraper — Search, Videos, Danmaku & Comments
Pricing
from $3.00 / 1,000 bilibili video extracteds
Bilibili 哔哩哔哩 Scraper — Search, Videos, Danmaku & Comments
Fast zero-cookie Bilibili (B站) scraper for keyword video search, full video metadata, timestamped live Danmaku (弹幕) XML with peak-moment analytics, top comments, popular rankings, and hot search trends. 512MB pure HTTP, WBI-signed, MCP & Pay-Per-Event ready.
Pricing
from $3.00 / 1,000 bilibili video extracteds
Rating
0.0
(0)
Developer
方圆 方
Maintained by CommunityActor stats
0
Bookmarked
2
Total users
1
Monthly active users
2 hours ago
Last modified
Categories
Features
Share
Bilibili All-in-One Scraper
Retrieve Bilibili video search results, video metadata, timestamped danmaku, top-level comments, rankings, and hot-search keywords through one Actor.
Actor: flowery_bluebird_jay/bilibili-all-in-one-scraper
Store: https://apify.com/flowery_bluebird_jay/bilibili-all-in-one-scraper
This implementation uses Python and HTTP requests with a 512 MB default memory configuration. It attempts session-cookie bootstrap and WBI signing without requiring a supplied login cookie. Public access can still be blocked by Bilibili, geography, rate limits, account requirements, or API changes. It does not launch a browser, download video files, collect nested comment replies, or promise a complete danmaku history.
Choose a workflow
mode | Inputs | Dataset records |
|---|---|---|
search | keywords | video_search, optionally enriched and containing danmaku/comments |
video | videoInputs | video, optionally containing danmaku/comments |
danmaku | videoInputs | danmaku: video metadata plus one XML summary and samples |
comments | videoInputs | One comment record per returned top-level comment |
trending | Optional trendingCategoryRid | hot_search keywords plus trending_video rankings; falls back to popular videos |
For example, use search for creator discovery, video mode for a known-video monitoring list, danmaku mode for timestamped audience reactions, and comments mode for text analysis. Trends combine two independently available sources and can contain more records than maxVideos.
Quick start
Paste this input into the Actor and run it:
{"mode": "search","keywords": ["AI Agent"],"maxVideos": 5,"enrichVideoDetails": true,"includeDanmaku": false,"includeComments": false}
To inspect a video and its available danmaku:
{"mode": "danmaku","videoInputs": ["BV1GJ411x7h7"],"maxDanmakuPerVideo": 200}
IDs and URLs must be supplied as strings. Direct modes accept an exact BV... ID, a positive av123 / 123 ID, a Bilibili video URL, a watch-later fragment containing a video ID, or a https://b23.tv/... short link. URLs with unrelated hosts, embedded credentials, or nonstandard ports are rejected. Every redirect is checked before it is followed. A ?p=2 parameter does not select a different part: the Actor uses the main CID returned by the video API.
Complete input reference
Omitted properties use the defaults below. JSON types are validated before HTTP requests or proxy setup: strings such as "false" and "15" are not converted into booleans or integers. Numeric values outside their supported range are rejected. Blank array entries are removed, and duplicate entries are processed once.
| Property | Type | Default | Meaning |
|---|---|---|---|
mode | string | "search" | search, video, danmaku, comments, or trending |
keywords | string[] | ["AI Agent"] | Search terms; applies only to search mode. Explicit [] exits without data requests. |
searchOrder | string | "totalrank" | totalrank relevance, click views, pubdate newest, dm danmaku, stow favorites |
videoInputs | string[] | ["https://www.bilibili.com/video/BV1GJ411x7h7"] | Direct-mode video inputs. Explicit [] exits without data requests. |
maxVideos | integer | 15 | 1–200 videos per keyword, or videos in the trending list. Not a global record cap. |
enrichVideoDetails | boolean | true | Search only: fetch details and tags. On failure, retain the search row. Search-only rows have cid: 0; enable enrichment for danmaku. |
includeDanmaku | boolean | false | Search/video only: embed a danmaku summary. Danmaku mode always fetches it. Other direct modes ignore this flag. |
maxDanmakuPerVideo | integer | 200 | 1–3000 chronological samples. Summary counts use all valid entries in the available XML, before sampling. |
includeComments | boolean | false | Search/video only: embed comments. Comments mode always fetches them. Other direct modes ignore this flag. |
maxCommentsPerVideo | integer | 20 | 1–200 top-level comments per video; availability and API pagination may yield fewer. |
commentSort | string | "hot" | hot or latest; applies to comment retrieval |
trendingCategoryRid | integer | 0 | 0–1000000000 category ID; 0 means all. A popular-feed fallback is not category-specific. |
cookieString | string | "" | Optional secret, single-line Cookie header. Empty attempts automatic bootstrap. Never include cookies in shared input examples. |
requestDelayMs | integer | 350 | 100–5000 milliseconds between HTTP requests, plus small random jitter |
proxyConfiguration | object | {"useApifyProxy": false} | Apify proxy configuration; proxyUrls may supply custom HTTP(S) proxies. Proxy fees and availability depend on the account. |
A complete input with every property:
{"mode": "video","keywords": ["AI Agent"],"searchOrder": "totalrank","videoInputs": ["https://www.bilibili.com/video/BV1GJ411x7h7"],"maxVideos": 15,"enrichVideoDetails": true,"includeDanmaku": true,"maxDanmakuPerVideo": 200,"includeComments": true,"maxCommentsPerVideo": 20,"commentSort": "hot","trendingCategoryRid": 0,"cookieString": "","requestDelayMs": 350,"proxyConfiguration": {"useApifyProxy": false}}
Output and limits
Results go to the default Apify dataset. The Actor output link named results points to that dataset's items endpoint. JSON preserves nested danmaku/comments; CSV or tabular exports may need flattening. Shapes vary by workflow: un-enriched search rows omit duration_sec, category_v2, and engagement_rate_pct, while direct and enriched video records include them. source_input belongs to direct video/danmaku records; comments use the associated video identity.
The following is an illustrative payload using the actual output keys, with synthetic text and counts. It is not a live result or a claim about the sample video's current metrics:
{"status": "ok","record_type": "video","source_keyword": "","bvid": "BV1GJ411x7h7","aid": 123,"cid": 456,"url": "https://www.bilibili.com/video/BV1GJ411x7h7","title": "Illustrative video title","description": "Illustrative description","category": "Technology","category_v2": "Technology","cover_url": "https://i0.hdslb.com/bfs/archive/example.jpg","duration_sec": 120,"duration_text": "02:00","published_at_unix": 1700000000,"published_at_iso": "2023-11-14T22:13:20+00:00","author_name": "Example creator","author_mid": "7","author_avatar_url": "https://i0.hdslb.com/bfs/face/example.jpg","author_space_url": "https://space.bilibili.com/7","views": 1000,"likes": 100,"coins": 10,"favorites": 20,"shares": 5,"danmaku_count": 8,"comments_count": 3,"engagement_rate_pct": 13.5,"tags": ["AI"],"scraped_at": "2026-11-27T00:00:00+00:00","source_input": "BV1GJ411x7h7","danmaku": {"total_danmaku_in_xml": 1,"peak_10s_window_start_sec": 10,"peak_10s_window_label": "00:10-00:20","peak_10s_danmaku_count": 1,"top_phrases": [{"phrase": "Great explanation", "count": 1}],"danmaku_items": [{"time_sec": 12.5,"time_formatted": "00:12","mode": 1,"font_size": 25,"color_hex": "#ffffff","sent_at_iso": "2023-11-14T22:13:20+00:00","text": "Great explanation"}]},"comments": [{"rpid": "1","author_name": "Example viewer","author_mid": "8","author_level": 5,"is_vip": false,"message": "Helpful example","likes": 2,"replies_count": 0,"location": "","created_at_iso": "2023-11-14T22:13:20+00:00"}]}
Comments mode emits the comment fields shown above at the top level, plus status, record_type: "comment", bvid, aid, title, url, and scraped_at. Hot-search records contain record_type: "hot_search", rank, keyword, show_name, icon_url, search_url, and scraped_at. Trending video records use the video shape plus rank and ranking_rid.
A valid empty API list is distinct from an unavailable source. Search tries its alternate endpoint when an HTTP request, JSON response, application error code, or collection shape fails; if both endpoints fail, it emits an uncharged search error record. Ranking similarly tries both signed and unsigned variants before the trending workflow tries the popular feed. A successful explicit empty list remains a valid, uncharged result, including when it comes from a fallback after another source failed. If the ranking variants and popular feed all fail, trending emits an uncharged error record instead of reporting zero matches as a successful extraction.
A failed direct item produces an uncharged extraction-error record, allowing subsequent inputs to continue:
{"status": "error","record_type": "video","source_input": "invalid-id","error": "Video input must be a BV/AV ID or a Bilibili URL","scraped_at": "2026-11-27T00:00:00+00:00"}
Search failures use record_type: "video_search" and source_keyword. Optional add-on failures set danmaku_error or comments_error on the otherwise usable video. An empty result is valid and carries no extraction events. A parsed empty danmaku XML document is a successful batch with zero items, so it still uses the batch event.
The danmaku endpoint returns the XML currently available for the main video CID. It is not a historical archive or a live subscription. Analytics exclude malformed timestamp rows; total_danmaku_in_xml counts valid, nonblank parsed entries. Ten-second peaks and repeated phrases summarize that document only. View/like counters are snapshots; engagement rate is (likes + coins + favorites + shares) / views * 100, with 0 when views are absent.
Configured pay-per-event rates
These are the suggested rates in this repository's .actor/pay_per_event_plan.json, in USD. They do not verify the live Store billing configuration. Check the Store pricing shown before running the Actor. Platform usage, proxy charges, taxes, or plan terms may apply separately.
| Event | 1 event | 100 events | 1,000 events | Trigger |
|---|---|---|---|---|
apify-actor-start | $0.005 | $0.50 | $5.00 | Platform-managed run start; the source does not charge it manually |
video-scraped | $0.003 | $0.30 | $3.00 | One saved search/video metadata record, including a fallback search row |
danmaku-batch | $0.004 | $0.40 | $4.00 | One saved successfully parsed XML batch, including an empty parsed batch |
comment-scraped | $0.0005 | $0.05 | $0.50 | One saved comment, embedded or emitted as its own record |
trending-item | $0.001 | $0.10 | $1.00 | One saved hot-search keyword or trending video |
Embedded add-ons create additional events: a video with one danmaku batch and 20 returned comments requests $0.003 + $0.004 + 20 × $0.0005 = $0.017, before run-start and other applicable fees. Comments mode requests only comment events; danmaku mode requests only batch events. Error records are not charged extraction events. Events are requested after a dataset write succeeds; billing failures are logged. Dataset delivery and charging are separate operations, so a run interrupted between them is not an atomic transaction. Local --local execution calls neither Apify dataset APIs nor PPE APIs.
Python SDK
Install apify-client in your application environment and export APIFY_TOKEN. This example starts a real, potentially billable Actor run when executed:
import osfrom apify_client import ApifyClientclient = ApifyClient(os.environ["APIFY_TOKEN"])run = client.actor("flowery_bluebird_jay/bilibili-all-in-one-scraper").call(run_input={"mode": "comments","videoInputs": ["BV1GJ411x7h7"],"maxCommentsPerVideo": 20,"commentSort": "hot",})if run is None or run["status"] != "SUCCEEDED":raise RuntimeError(f"Actor did not succeed: {run}")for item in client.dataset(run["defaultDatasetId"]).iterate_items():print(item)
Node.js SDK
Install apify-client, use a .mjs file or an ESM project, and export APIFY_TOKEN. This starts a real run and reads dataset pages:
import { ApifyClient } from 'apify-client';const client = new ApifyClient({ token: process.env.APIFY_TOKEN });const run = await client.actor('flowery_bluebird_jay/bilibili-all-in-one-scraper').call({mode: 'search',keywords: ['AI Agent'],maxVideos: 5,enrichVideoDetails: true,});if (run.status !== 'SUCCEEDED') throw new Error(`Actor status: ${run.status}`);const dataset = client.dataset(run.defaultDatasetId);for (let offset = 0; ; ) {const page = await dataset.listItems({ offset, limit: 1000, clean: true });for (const item of page.items) console.log(item);offset += page.items.length;if (page.items.length === 0 || offset >= page.total) break;}
n8n and Make: HTTP setup
Use an n8n HTTP Request node or Make HTTP / Make a request module. Store the token in the platform's credential/secret storage.
- Set method to
POSTand URL tohttps://api.apify.com/v2/acts/flowery_bluebird_jay~bilibili-all-in-one-scraper/runs. - Add
Authorization: Bearer YOUR_APIFY_TOKENandContent-Type: application/json. Send the quick-start input as the JSON body. In Make, enable response parsing. - Save the returned
data.idanddata.defaultDatasetId. PollGET https://api.apify.com/v2/actor-runs/RUN_IDwith the same authorization untildata.statusisSUCCEEDED,FAILED,TIMED-OUT, orABORTED. Use a wait/delay between polls. - On success, request
GET https://api.apify.com/v2/datasets/DATASET_ID/items?format=json&clean=truewith authorization. Addoffset/limitfor large datasets. Map each returned JSON record into the next node/module. - Route failed run statuses and
status: "error"dataset records to an error-handling path. Do not blindly repeat a POST after a workflow timeout: another POST starts another potentially billable run. Reuse the saved run ID to resume polling.
Claude Desktop and Cursor: local MCP bridge
If you already have the companion apify_cn_mcp_server installed locally, use its Node entry point. Replace /ABSOLUTE/PATH with the absolute directory containing that project; do not point this at the Actor's Python entry point.
The same mcpServers block can be used in Claude Desktop's MCP configuration or Cursor's MCP configuration:
{"mcpServers": {"apify-cn": {"command": "node","args": ["/ABSOLUTE/PATH/apify_cn_mcp_server/src/server.mjs"],"env": {"APIFY_TOKEN": "YOUR_APIFY_TOKEN"}}}}
Restart/reload the MCP client and check that the bridge exposes the bilibili_video_danmaku tool. It accepts the Actor input fields directly. Call it with:
{"mode": "danmaku","videoInputs": ["BV1GJ411x7h7"],"maxDanmakuPerVideo": 200}
A useful request is: “Use bilibili_video_danmaku to retrieve danmaku for BV1GJ411x7h7, with at most 200 samples.” The companion server is separate from this Actor; its regression tests and integration acceptance are separate from the Actor-only offline suite.
Billing notice: calling the MCP tool can launch an Apify Actor run with the configured token and incur PPE and other applicable charges. Local MCP transport does not make the remote extraction free. Use an appropriately scoped token and your client's tool approval controls.
Reliability and resource choices
All data, bootstrap, XML, and short-link HTTP calls have an 18-second timeout per network operation. Timeout failures, HTTP 429, and HTTP 5xx responses receive up to three total attempts with exponential backoff and jitter. Other HTTP 4xx responses, malformed JSON/XML, invalid inputs, and non-timeout transport errors are not retried by that request. Search can try its alternate endpoint, and trending can try the popular feed; those are source fallbacks rather than a retry of a non-retryable request. Pagination is bounded, comments and popular items are deduplicated, and missing/wrong nested object types are treated as unavailable fields.
The 512 MB setting is a configured default, not a measured peak-memory guarantee. Pure HTTP avoids browser startup and browser processes and suits structured API extraction. Browser-based approaches can be useful for interactive login, rendered-page behavior, or data that an HTTP endpoint no longer exposes, but they require a different runtime and maintenance model. This Actor cannot execute JavaScript challenges or bypass access controls. No speed, success-rate, cost-savings, or competitor benchmark is asserted here.
FAQ
Do I need cookies?
A supplied cookie is optional. Automatic session bootstrap is attempted, but Bilibili may still require login or deny an endpoint. A cookie cannot guarantee extraction.
Why are there fewer comments or danmaku than the video counter?
The XML/feed may be partial, comments can be unavailable or moderated, and only top-level comments are requested. Limits are upper bounds, not promised quantities.
Why did search produce a record without a danmaku object?
Un-enriched search results lack the video CID. Enable enrichVideoDetails; if enrichment or the XML request fails, inspect danmaku_error. Search metadata remains available when possible.
Does maxVideos cap the entire run?
No. It applies to each keyword or the trending video list. Embedded comments and danmaku have their own limits, while hot-search keywords are additional trending records. Direct inputs are processed once each.
Are rankings always category-specific?
The ranking request uses your category ID. The popular-feed fallback does not, and ranking_rid records the requested category ID rather than proving the fallback was category-filtered.
Can it scrape private videos or download media?
No supported workflow downloads media or promises private, deleted, region-restricted, historical, or login-restricted data. Only request data you are permitted to access and use.
Does an error mean the run is free?
Extraction error records have no extraction event, but a run-start charge and other platform/proxy costs can still apply. Successful records and add-ons collected before an error can also be charged.
Local development and offline tests
The Python package can use its stdlib HTTP fallback when httpx is absent. Cloud packaging installs the dependencies from requirements.txt. A local extraction still contacts Bilibili when executed:
$python3 -m src.main --local --input input.json --output output_bilibili.json
The regression suite uses stdlib unittest/mock, replaces SDK/HTTP imports with offline stubs, and makes no network requests or paid runs:
$PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v
Offline tests validate parsing, input boundaries, response shapes, retry policy, output branches, and PPE calls. They do not establish current Bilibili API access, published Store pricing, proxy behavior, a live build, or MCP integration acceptance.