# Bilibili Comment Sentiment (`kjames2001/bilibili-comment-sentiment`) Actor

Scrape Bilibili videos and comments, then run AI-powered sentiment analysis. Get sentiment scores, topics, and audience insights for Chinese market research.

- **URL**: https://apify.com/kjames2001/bilibili-comment-sentiment.md
- **Developed by:** [James Huang](https://apify.com/kjames2001) (community)
- **Categories:** Social media, AI
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## 🧠 Bilibili Sentiment Analysis | B站评论分析 & Chinese Social Media Sentiment

[![Apify Actor](https://img.shields.io/badge/Apify-Actor-blue)](https://apify.com/store)
[![AI Sentiment](https://img.shields.io/badge/AI-Sentiment_Analysis-green)](https://apify.com/store)
[![Node.js 20](https://img.shields.io/badge/Node.js-20-green)](https://nodejs.org)
[![Pay Per Event](https://img.shields.io/badge/Pricing-Pay_per_Event-orange)](https://apify.com/pricing)

> Scrape **Bilibili** videos and comments, then run AI-powered **bilibili sentiment analysis** on the data. Get sentiment scores, topic extraction, emotion detection, and **chinese audience insights** from **B站评论分析**. The ultimate tool for **china market research sentiment** and **chinese social media sentiment** analysis on China's largest video platform — with both rule-based and GPT-4o-mini LLM modes.

### Features

- **Bilibili Comments Analysis** — Extract and analyze comments from videos matching your keywords
- **AI-Powered Sentiment** — Optional LLM-based analysis using OpenAI GPT-4o-mini for deep insights
- **Rule-Based Fallback** — Built-in Chinese sentiment lexicon with 70+ positive/negative words and negation detection
- **Sentiment Scoring** — Per-comment sentiment classification (positive/negative/neutral) with scores
- **Aggregate Analysis** — Per-video sentiment breakdown with percentages, overall sentiment, and sentiment score
- **Top Keywords** — Most frequently used positive and negative words across all comments
- **Topic Extraction** — When using LLM mode, extract discussion topics from each comment
- **Spam Detection** — LLM mode includes spam classification
- **Multi-Keyword** — Analyze multiple search keywords in a single run
- **No Browser Needed** — Direct API access, fast and efficient

### Use Cases

- **Brand Monitoring** — Track sentiment around your brand on B站 (Bilibili)
- **China Market Research** — Understand **chinese social media sentiment** for product launches
- **Audience Analysis** — Get **chinese audience insights** from real user comments
- **Content Evaluation** — Measure audience reception of videos and campaigns
- **Competitor Analysis** — Compare sentiment around competing brands or products
- **Trend Detection** — Identify emerging positive/negative sentiment shifts
- **Academic Research** — Study Chinese online discourse and social media patterns
- **Bilibili AI Analysis** — Leverage AI to process thousands of Chinese comments automatically
- **Crisis Monitoring** — Detect negative sentiment spikes around your brand in real-time

### Input Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `searchKeywords` | array | **Yes** | `["华为"]` | Keywords to search on Bilibili |
| `maxVideos` | int | No | `10` | Max videos to analyze per keyword (1-100) |
| `maxCommentsPerVideo` | int | No | `50` | Max comments to extract per video (1-500) |
| `analysisType` | select | No | `full` | `sentiment` (basic) or `full` (sentiment + topics + emotion + spam) |
| `openaiApiKey` | string | No | `""` | OpenAI API key for LLM analysis. If empty, uses rule-based analysis |
| `proxyConfiguration` | object | No | Apify proxy | Proxy config (residential recommended outside China) |

### Output Fields

#### Video Object with Sentiment

| Field | Type | Description |
|---|---|---|
| `bvid` | string | Bilibili video ID |
| `aid` | int | Bilibili video ID (AV format) |
| `title` | string | Video title |
| `author` | string | Creator name |
| `viewCount` | int | Total views |
| `likeCount` | int | Total likes |
| `replyCount` | int | Total comments |
| `publishDate` | string | ISO date string |
| `tags` | array | Video tags |
| `searchKeyword` | string | Keyword that matched this video |
| `sentimentSummary` | object | Aggregate sentiment analysis (see below) |
| `comments` | array | Analyzed comments (see below) |
| `scrapedAt` | string | ISO timestamp |

#### Sentiment Summary Object

| Field | Type | Description |
|---|---|---|
| `sentimentBreakdown.positive` | int | Count of positive comments |
| `sentimentBreakdown.negative` | int | Count of negative comments |
| `sentimentBreakdown.neutral` | int | Count of neutral comments |
| `sentimentBreakdown.positivePct` | int | Positive percentage |
| `sentimentBreakdown.negativePct` | int | Negative percentage |
| `sentimentBreakdown.neutralPct` | int | Neutral percentage |
| `overallSentiment` | string | Overall: positive, negative, or neutral |
| `sentimentScore` | float | Score from -1.0 to 1.0 |
| `topPositiveWords` | array | Top positive words with frequency |
| `topNegativeWords` | array | Top negative words with frequency |
| `totalCommentsAnalyzed` | int | Number of comments analyzed |

#### Comment Object with Analysis

| Field | Type | Description |
|---|---|---|
| `content` | string | Comment text (Chinese) |
| `author` | string | Commenter name |
| `likes` | int | Comment likes |
| `timestamp` | string | ISO date string |
| `sentimentAnalysis.sentiment` | string | positive / negative / neutral |
| `sentimentAnalysis.score` | float/int | Sentiment score |
| `sentimentAnalysis.positiveWords` | array | Positive words found (rule-based) |
| `sentimentAnalysis.negativeWords` | array | Negative words found (rule-based) |
| `sentimentAnalysis.topics` | array | Discussion topics (LLM mode only) |
| `sentimentAnalysis.emotion` | string | Detected emotion (LLM mode only) |
| `sentimentAnalysis.is_spam` | bool | Spam classification (LLM mode only) |

### Analysis Modes

#### Rule-Based (No API Key)

- Fast, free, no external dependencies
- Chinese sentiment lexicon with 70+ words
- Negation detection (不/没/别/无/非 prefixes)
- Positive/negative/neutral classification
- Word frequency aggregation

#### LLM-Powered (With OpenAI API Key)

- GPT-4o-mini for deep Chinese language understanding
- Topic extraction from each comment
- Emotion detection (joy, anger, surprise, etc.)
- Spam/ad detection
- More accurate sentiment scoring (-1.0 to 1.0)
- Better handling of sarcasm and context

### How It Works

1. **Input keywords** — Provide brand or topic keywords to search on Bilibili (e.g., "华为", "iPhone")
2. **Video scraping** — The actor searches Bilibili and fetches matching videos with metadata
3. **Comment extraction** — Comments are scraped from each video via Bilibili's reply API
4. **Sentiment analysis** — Each comment is classified as positive/negative/neutral using rule-based or LLM analysis
5. **Aggregation** — Per-video sentiment summaries with percentages, top keywords, and overall scores
6. **Structured JSON output** — Results saved to Apify dataset, ready for dashboards and reports

### Pricing

This Actor uses **pay-per-event** pricing:

| Event | Cost |
|---|---|
| Actor start (1GB RAM) | $0.01 |
| Video analyzed | $0.02 |
| Comment sentiment analyzed | $0.005 |

**Example**: 3 keywords × 10 videos × 50 comments = $0.01 + (30 × $0.02) + (1500 × $0.005) = **$8.16**

### Technical Details

This **bilibili sentiment analysis** tool combines scraping and AI analysis:

- Search: `api.bilibili.com/x/web-interface/search/type`
- Comments: `api.bilibili.com/x/v2/reply/main`
- Sentiment: Rule-based Chinese lexicon or OpenAI GPT-4o-mini API

No headless browser needed. Cookie-based access handled automatically. Residential proxies recommended outside China.

#### Runtime & SDK

- **Runtime:** Node.js 20
- **SDK:** Apify SDK v3 + Crawlee v3
- **AI:** OpenAI GPT-4o-mini (optional, for LLM mode)

### Why Use This vs Alternatives?

| Feature | This Actor | Chinese Brand Monitor | Bilibili Scraper (comments only) |
|---|---|---|---|
| Sentiment scoring | ✅ | ✅ (basic) | ❌ |
| Rule-based + LLM modes | ✅ | ❌ | ❌ |
| Per-comment analysis | ✅ | ❌ | ❌ |
| Emotion detection | ✅ | ❌ | ❌ |
| Topic extraction | ✅ | ❌ | ❌ |
| Spam detection | ✅ | ❌ | ❌ |
| Top keyword extraction | ✅ | ❌ | ❌ |
| Multi-keyword support | ✅ | ✅ | ❌ |
| Aggregate summaries | ✅ | ✅ | ❌ |
| Free rule-based mode | ✅ | ❌ | N/A |

### FAQ

<details>
<summary><b>Do I need an OpenAI API key?</b></summary>
No. If you leave the `openaiApiKey` field empty, the actor uses a built-in rule-based Chinese sentiment lexicon with 70+ words and negation detection. This is free and requires no external API. The LLM mode provides deeper analysis (topics, emotions, spam detection) but requires an OpenAI key.
</details>

<details>
<summary><b>What languages does the sentiment analysis support?</b></summary>
The actor is optimized for Chinese comments (中文评论). The rule-based lexicon covers Chinese sentiment words. The LLM mode (GPT-4o-mini) handles Chinese naturally, including sarcasm and context.
</details>

<details>
<summary><b>Can I analyze multiple brands at once?</b></summary>
Yes. Provide multiple keywords in the `searchKeywords` array. Each keyword is searched independently, and results include the `searchKeyword` field so you can group by brand.
</details>

<details>
<summary><b>Do I need a proxy?</b></summary>
If running from outside China, residential proxies are recommended to avoid IP-based rate limiting on Bilibili's API.
</details>

### Keywords

`bilibili sentiment analysis` · `b站评论分析` · `chinese social media sentiment` · `bilibili comment analysis` · `chinese audience insights` · `china market research sentiment` · `bilibili ai analysis` · `bilibili nlp` · `chinese sentiment analysis` · `bilibili brand monitoring` · `b站情感分析` · `bilibili opinion mining` · `chinese comment sentiment` · `bilibili emotion detection` · `bilibili topic extraction` · `chinese language sentiment` · `bilibili comment scraper` · `china social listening` · `bilibili sentiment api` · `chinese nlp sentiment` · `b站舆情` · `bilibili sentiment score` · `bilibili comment mining` · `chinese text sentiment analysis`

# Actor input Schema

## `searchKeywords` (type: `array`):

Keywords to search on Bilibili. e.g. \["华为", "iPhone"]

## `maxVideos` (type: `integer`):

Maximum videos to analyze per keyword.

## `maxCommentsPerVideo` (type: `integer`):

Maximum comments to extract and analyze per video.

## `analysisType` (type: `string`):

Type of AI analysis to perform.

## `openaiApiKey` (type: `string`):

OpenAI API key for LLM analysis. If not provided, uses rule-based sentiment analysis.

## `proxyConfiguration` (type: `object`):

Apify proxy configuration.

## Actor input object example

```json
{
  "searchKeywords": [
    "华为"
  ],
  "maxVideos": 10,
  "maxCommentsPerVideo": 50,
  "analysisType": "full",
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "searchKeywords": [
        "华为"
    ],
    "openaiApiKey": "",
    "proxyConfiguration": {
        "useApifyProxy": true
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("kjames2001/bilibili-comment-sentiment").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "searchKeywords": ["华为"],
    "openaiApiKey": "",
    "proxyConfiguration": { "useApifyProxy": True },
}

# Run the Actor and wait for it to finish
run = client.actor("kjames2001/bilibili-comment-sentiment").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "searchKeywords": [
    "华为"
  ],
  "openaiApiKey": "",
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}' |
apify call kjames2001/bilibili-comment-sentiment --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=kjames2001/bilibili-comment-sentiment",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/uIcEDlPe9kYRWujdE/builds/BsaibI0pauOkLa9C5/openapi.json
