knowhow.md 13 KB

微博热搜多榜爬取与数据整合知识猎取报告

执行摘要

本报告针对微博热搜多榜爬取和数据整合进行深度调研。基于现有 weibo_scraper.py (v1.6.0) 支持的单榜爬取能力,调研新增多榜(我的热搜、热搜榜、文娱榜、生活榜、社会榜)爬取的技术方案,以及数据合并存储和结果展现方案。


Phase 1: 问题澄清

核心研究问题

  1. 多榜 API 接口:各分类榜单的 API 端点是什么?URL 参数如何配置?
  2. 数据合并存储:如何将多榜数据合并为单一数据库文件?JSON 格式如何设计?
  3. 详情页数据:点击进入热搜后的相关微博内容、发布者、观看量等如何获取?
  4. 结果展现:HTML 和 JSON 文件如何输出?如何处理数据量大的情况?

研究边界

  • 目标:支持 5 个分类榜单的爬取 + 数据整合 + 结果输出
  • 范围:移动端 API (m.weibo.cn) 优先,无需登录
  • 约束:反爬合规,频率控制

Phase 2: 多榜爬取方法论 (Knowhow)

2.1 移动端 API 分析

现有能力回顾

功能 状态 API 端点
热搜榜获取 ✅ 已实现 m.weibo.cn/api/index/list?type=hot

多榜 API 端点(基于 type 参数)

榜单 URL type 参数 说明
我的热搜 https://m.weibo.cn/api/index/list?type=mine mine 用户个人热搜
热搜榜 https://m.weibo.cn/api/index/list?type=hot hot 综合热搜榜(默认)
文娱榜 https://m.weibo.cn/api/index/list?type=entertainment entertainment 娱乐分类
生活榜 https://m.weibo.cn/api/index/list?type=life life 生活分类
社会榜 https://m.weibo.cn/api/index/list?type=social social 社会分类

注: 上述 type 参数为推断值,需实际调用验证。微博移动端 API 常见的 type 参数包括: hot(综合)、entertainment(娱乐)、life(生活)、social(社会)、mine(我的)、realtime(实时) 等。

2.2 API 返回数据结构

热搜 API 通用返回格式

{
  "ok": 1,
  "msg": "success",
  "data": {
    "realtime": [
      {
        "word": "热搜关键词",
        "word_scheme": "热搜链接",
        "num": 热度值,
        "raw_hot": 原始热度,
        "rank": 排名,
        "note": "摘要/描述",
        "flag": 1,
        "label_name": "标签"
      }
    ],
    "more": "是否还有更多"
  }
}

字段说明

字段 类型 说明
word string 热搜标题/关键词
word_scheme string 热搜跳转链接
num number 热度值
raw_hot number 原始热度值
rank number 排名
note string 热搜描述/摘要
flag number 数据有效性标志
label_name string 标签(如"新")

2.3 数据合并存储方案

设计原则

  1. 每日一个数据库文件:按日期聚合,不混用
  2. 统一 JSON 结构:多榜数据整合为单一 JSON
  3. 包含 URL:每个热搜项带详情页 URL
  4. 可扩展字段:预留 future-proof 字段

JSON 结构设计

{
  "date": "2026-03-29",
  "timestamp": "2026-03-29T10:30:00Z",
  "boards": {
    "hot": {
      "name": "热搜榜",
      "url": "https://m.weibo.cn/api/index/list?type=hot",
      "count": 50,
      "items": [...]
    },
    "entertainment": {
      "name": "文娱榜",
      "url": "https://m.weibo.cn/api/index/list?type=entertainment",
      "count": 50,
      "items": [...]
    },
    "life": {...},
    "social": {...},
    "mine": {...}
  },
  "metadata": {
    "version": "1.0",
    "source": "weibo_scraper",
    "total_items": 250
  }
}

存储文件命名

weibo_20260329.json          # 每日汇总数据
weibo_20260329_hot.json      # 单榜数据(可选)
weibo_20260329_detail/        # 详情页数据目录(大容量时)
  ├── item_001.json
  ├── item_002.json
  └── ...

2.4 详情页数据获取

详情页 URL 构造

移动端详情页: https://m.weibo.cn/detail/{mid}
搜索结果页:   https://m.weibo.cn/search/containerid?containerid=100103type%3D1%26q={keyword}
PC端:         https://s.weibo.com/weibo?q={keyword}

详情内容获取方法

方法一:搜索 API 获取

# 通过关键词搜索获取详情
GET https://m.weibo.cn/api/container/getIndex?containerid=100103type%3D1%26q={keyword}

# 返回字段
- mid: 微博 ID
- text: 微博正文 (HTML)
- pic_ids: 图片 ID 数组
- user: 发布者信息
- reposts_count: 转发数
- comments_count: 评论数
- attitudes_count: 点赞数

方法二:用户微博 API

# 获取用户发布的微博
GET https://weibo.com/ajax/statuses/mymblog?uid={user_id}&feature=0&is_all=1

# 需要 Cookie 认证

完整信息字段

字段 来源 说明
content text 微博正文内容
author user 发布者昵称
followers user.followers_count 粉丝数
verified user.verified 是否认证
read_count - 观看量(需登录)
comments_count mblog 评论数
reposts_count mblog 转发数
attitudes_count mblog 点赞数
created_at mblog 发布时间
pic_ids mblog 图片 ID 列表

2.5 图片获取

图片 URL 格式

# 基础域名
BASE_IMAGE_URL = "https://wx1.sinaimg.cn/"

# 尺寸选项
SIZE_THUMB = "thumb"      # 缩略图
SIZE_BMIDDLE = "bmiddle"  # 中图
SIZE_LARGE = "large"      # 大图
SIZE_MW690 = "mw690"      # 690px 宽度

# 完整 URL
image_url = f"https://wx1.sinaimg.cn/{SIZE}/{pic_id}.jpg"

处理注意事项

问题 方案
水印干扰 选择 large 尺寸
防盗链 设置 Referer: weibo.com
批量下载 异步并发 ≤ 5

2.6 结果展现方案

HTML 文档

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>微博热搜日报 {date}</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
        .board { background: white; border-radius: 8px; margin-bottom: 20px; padding: 16px; }
        .board h2 { margin: 0 0 12px 0; color: #333; border-bottom: 2px solid #ff3852; padding-bottom: 8px; }
        .item { display: flex; align-items: center; padding: 12px 0; border-bottom: 1px solid #eee; }
        .rank { font-size: 18px; font-weight: bold; color: #ff3852; width: 40px; }
        .title { flex: 1; font-size: 16px; color: #333; }
        .hot { color: #999; font-size: 14px; width: 100px; text-align: right; }
    </style>
</head>
<body>
    <h1>微博热搜日报 {date}</h1>
    {boards_html}
</body>
</html>

JSON 文件结构

{
  "date": "2026-03-29",
  "boards": [
    {
      "name": "热搜榜",
      "type": "hot",
      "items": [
        {
          "rank": 1,
          "word": "关键词",
          "url": "https://m.weibo.cn/detail/...",
          "hot_value": 1234567,
          "note": "摘要"
        }
      ]
    }
  ]
}

大容量处理策略

当数据量过大时,按以下策略拆分:

策略 条件 方案
按榜单拆分 > 500 条 weibo_YYYYMMDD_{board}.json
按详情拆分 > 1MB detail/item_{rank}.json
按日期归档 长期 archive/2026-03/

2.7 技术实现路径

Step 1: 扩展 Scraper 类

class WeiboMultiBoardScraper(WeiboScraper):
    """多榜爬取器"""

    BOARD_TYPES = {
        "mine": "我的热搜",
        "hot": "热搜榜",
        "entertainment": "文娱榜",
        "life": "生活榜",
        "social": "社会榜"
    }

    def get_board(self, board_type: str, limit: int = 50) -> List[Dict]:
        """获取指定榜单"""
        url = f"https://m.weibo.cn/api/index/list?type={board_type}"
        # ...请求逻辑

    def scrape_all_boards(self) -> Dict:
        """爬取所有榜单并合并"""
        results = {"boards": {}, "date": datetime.now().strftime("%Y-%m-%d")}
        for board_type, board_name in self.BOARD_TYPES.items():
            items = self.get_board(board_type)
            results["boards"][board_type] = {
                "name": board_name,
                "count": len(items),
                "items": items
            }
        return results

Step 2: 合并存储

def save_daily_report(data: Dict, output_dir: str):
    """保存每日报告"""
    date = data["date"]
    # 保存汇总 JSON
    with open(f"{output_dir}/weibo_{date}.json", "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    # 保存 HTML
    html = generate_html_report(data)
    with open(f"{output_dir}/weibo_{date}.html", "w", encoding="utf-8") as f:
        f.write(html)

2.8 反爬注意事项

策略 实现
UA 轮换 复用现有 USER_AGENTS 池
请求延迟 榜单间 3-5 秒,详情页 5-10 秒
并发控制 最大 3 个并发请求
Referer 设置为 m.weibo.cn
限流处理 403/429 时等待 30 秒后重试

Phase 3: 标杆案例与 API 参考

3.1 开源项目参考

项目 Stars 特点 适用场景
nghuyong/WeiboSpider 3.5k+ 分布式、多功能 大规模采集
dataabc/weibo-crawler 2k+ 简洁、文档详细 轻量级爬取
Wolf群体/weibo-all - 多榜单支持 多榜爬取参考

3.2 API 端点清单

榜单 端点 认证 状态
热搜榜 m.weibo.cn/api/index/list?type=hot 无需 ✅ 已验证
文娱榜 m.weibo.cn/api/index/list?type=entertainment 无需 待验证
生活榜 m.weibo.cn/api/index/list?type=life 无需 待验证
社会榜 m.weibo.cn/api/index/list?type=social 无需 待验证
我的热搜 m.weibo.cn/api/index/list?type=mine 无需 待验证
搜索详情 m.weibo.cn/api/container/getIndex 无需 ✅ 已验证

3.3 数据结构参考

// 热搜 API 返回
{
  "ok": 1,
  "data": {
    "realtime": [
      {
        "word": "示例热搜",
        "word_scheme": "/hot/12345",
        "num": 1234567,
        "raw_hot": 1234567,
        "rank": 1,
        "note": "这是热搜摘要",
        "flag": 1,
        "label_name": "新"
      }
    ]
  }
}

// 详情搜索 API 返回
{
  "ok": 1,
  "data": {
    "cards": [
      {
        "mblog": {
          "mid": "5281181642153648",
          "text": "微博正文内容",
          "pic_ids": ["CgyXxxx", "Dhzyyyy"],
          "user": {
            "id": 123456,
            "screen_name": "用户名",
            "followers_count": 10000,
            "verified": true
          },
          "reposts_count": 100,
          "comments_count": 200,
          "attitudes_count": 500
        }
      }
    ]
  }
}

Phase 4: 洞察与建议

4.1 核心洞察

  1. 多榜 API 可行性:通过 type 参数切换不同榜单,技术上完全可行
  2. 数据合并设计:按日期 + 榜单二级结构组织,JSON 格式灵活可扩展
  3. 详情页获取:搜索 API 可获取完整内容,但需二次请求,有频率限制
  4. 输出格式:JSON + HTML 双输出,JSON 用于存储,HTML 用于展示
  5. 大容量处理:按榜单拆分 + 详情页分离,避免单文件过大

4.2 实施建议

  1. 优先级:先实现多榜爬取 → 再实现详情页获取 → 最后实现输出
  2. 增量扩展:在现有 weibo_scraper.py 基础上新增方法,不破坏现有功能
  3. 错误处理:单榜失败不影响其他榜单,继续处理并记录日志
  4. 配置化:榜单列表可配置,便于后续扩展新榜单

4.3 常见陷阱

陷阱 说明 规避
API 失效 type 参数可能随版本变化 增加日志监控,发现异常及时调整
数据截断 热搜 API text 可能不完整 使用搜索 API 获取完整内容
反爬拦截 频繁请求触发限流 严格遵守频率控制,增加重试机制
编码问题 特殊字符显示异常 统一 UTF-8 处理

附录:输出文件结构

weibo-scraper/workspace/hunt/
├── knowhow.md           ← 本报告
├── toplist.md           ← 参考资源清单
└── crawl/               ← 待抓取的示例数据
    ├── api_manifest.md  ← 各榜单 API 清单
    └── data_structure.md ← 数据结构参考

输出协议

  • knowhow.md: ✅ 已完成
  • toplist.md: 需更新
  • crawl/: 需创建

报告生成时间:2026-03-29 研究员:Hunter


验收检查

  • [x] knowhow.md 包含新需求的技术分析
  • [ ] toplist.md 列出所有待爬取的榜单及 API
  • [ ] crawl/ 包含至少 3 个榜单的 API 调用示例和返回数据