You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用vk_api的wall.getComments获取全部评论数及用户ID?

解决vk_api获取墙贴全部评论时的KeyError问题

问题根源

KeyError通常出现在两种场景:

  • 当offset值超过实际评论总数时,VK API返回的响应中可能没有items字段
  • 错误访问了响应中不存在的键(比如字段名拼写错误)

解决方案

核心思路是先获取总评论数明确循环边界,再分页循环请求,同时添加异常处理和字段存在性检查:

  1. 先获取总评论数:调用wall.getComments时设置count=0,直接拿到count字段,避免盲目循环
  2. 分页循环请求:每次递增offset(步长100),直到offset大于等于总评论数时停止
  3. 字段存在性检查:每次请求后先判断items字段是否存在,再提取数据
  4. 处理API限制:添加请求延迟,避免触发VK API的频率限制

完整代码示例

import vk_api
import time

# 初始化VK API会话
vk_session = vk_api.VkApi(token='你的访问令牌')
vk = vk_session.get_api()

# 目标墙贴参数
post_id = 12345  # 替换为实际墙贴ID
owner_id = -123456  # 替换为实际所有者ID,群组ID需加负号

# 获取总评论数
try:
    init_response = vk.wall.getComments(owner_id=owner_id, post_id=post_id, count=0)
    total_comments = init_response['count']
except KeyError as e:
    print(f"初始化请求失败: 响应缺少字段 {e}")
    exit()
except vk_api.exceptions.ApiError as e:
    print(f"API权限错误: {e}")
    exit()

all_comment_user_ids = set()  # 用集合自动去重重复评论的用户
current_offset = 0

while current_offset < total_comments:
    try:
        # 请求当前页评论
        comment_response = vk.wall.getComments(
            owner_id=owner_id,
            post_id=post_id,
            count=100,
            offset=current_offset,
            fields='id'  # 仅请求必要字段,减少数据传输量
        )

        # 检查items字段是否存在
        if 'items' not in comment_response:
            print(f"偏移量 {current_offset} 未返回评论数据")
            current_offset += 100
            continue

        # 提取评论用户ID
        for comment in comment_response['items']:
            # from_id可能是用户ID(正数)或群组ID(负数)
            all_comment_user_ids.add(comment['from_id'])

        current_offset += 100
        time.sleep(0.3)  # 遵守VK API频率限制(每秒最多3次请求)

    except vk_api.exceptions.ApiError as e:
        print(f"API请求错误: {e}")
        break
    except KeyError as e:
        print(f"响应缺少字段 {e},跳过当前偏移量 {current_offset}")
        current_offset += 100
        continue

# 输出结果
print(f"墙贴总评论数: {total_comments}")
print(f"参与评论的独立用户/群组数量: {len(all_comment_user_ids)}")
print("所有评论用户/群组ID:")
print(all_comment_user_ids)

关键注意事项

  • 权限验证:确保你的访问令牌拥有wall权限,否则无法获取评论数据
  • Owner ID格式:群组ID必须以负号开头,用户ID为正数,格式错误会直接导致请求失败
  • 频率限制:VK API限制每秒最多3次请求,添加time.sleep(0.3)可避免被限流封禁
  • 去重处理:用集合存储用户ID可以自动过滤同一用户的多次评论

内容的提问来源于stack exchange,提问作者Ilnarildarovuch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:07:31