首页
/ 如何使用 zhihu-api:知乎非官方接口完整实用指南

如何使用 zhihu-api:知乎非官方接口完整实用指南

2026-02-06 04:22:19作者:鲍丁臣Ursa

zhihu-api 是一个专为开发者设计的非官方知乎 API 封装库,用 JavaScript 实现,提供简洁易用的接口,帮助你轻松获取和操作知乎平台数据。无论是数据分析、内容聚合还是自动化管理,这个工具都能满足你的需求。

📌 项目价值定位:为什么选择 zhihu-api?

核心优势

  • 简洁接口:直观的 API 设计,降低开发难度
  • 功能全面:覆盖用户、问题、回答、话题等核心数据
  • 灵活集成:可轻松整合到各种 Node.js 项目中

适用场景

  • 知乎数据采集与分析
  • 自动化内容管理
  • 社交数据监控
  • 知乎生态相关应用开发

🔧 零基础环境准备步骤

安装 Node.js 环境

确保你的系统已安装 Node.js(v6.0.0 或更高版本)。你可以通过以下命令检查 Node.js 版本:

node -v

获取项目代码

git clone https://gitcode.com/gh_mirrors/zhi/zhihu-api
cd zhihu-api

安装依赖包

npm install

🚀 基础操作:快速上手指南

项目初始化

// 引入 zhihu-api
const zhihu = require('./index');

// 配置请求头(必须)
zhihu.config({
  headers: {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Cookie': 'z_c0="你的z_c0 Cookie"; _xsrf="你的_xsrf Cookie"'
  }
});

💡 小贴士:Cookie 获取方法:登录知乎后,通过浏览器开发者工具(F12)在 Application 标签的 Cookies 中找到并复制 z_c0_xsrf 值。

获取用户信息

// 获取用户基本资料
zhihu.user.profile('用户名或用户ID')
  .then(profile => {
    console.log('用户信息:', profile);
    console.log('用户昵称:', profile.name);
    console.log('关注数:', profile.following_count);
    console.log('粉丝数:', profile.follower_count);
  })
  .catch(error => console.error('获取用户信息失败:', error));

获取问题及回答

// 获取问题详情
zhihu.question.get('问题ID')
  .then(question => {
    console.log('问题标题:', question.title);
    console.log('问题描述:', question.content);
    
    // 获取问题回答列表
    return zhihu.question.answers('问题ID', { limit: 5 });
  })
  .then(answers => {
    console.log('获取到', answers.length, '个回答');
    answers.forEach(answer => {
      console.log('回答作者:', answer.author.name);
      console.log('回答内容:', answer.content);
      console.log('点赞数:', answer.voteup_count);
    });
  })
  .catch(error => console.error('操作失败:', error));

📊 高级应用:实战案例

话题热门问题采集

// 获取话题下的热门问题
async function getHotQuestionsInTopic(topicId, limit = 10) {
  try {
    // 获取话题信息
    const topic = await zhihu.topic.get(topicId);
    console.log(`话题: ${topic.name} (${topic.id})`);
    console.log(`描述: ${topic.introduction}`);
    
    // 获取热门问题
    const hotQuestions = await zhihu.topic.hotQuestions(topicId, { limit });
    
    console.log(`\n热门问题列表 (共${hotQuestions.length}个):`);
    hotQuestions.forEach((question, index) => {
      console.log(`${index + 1}. ${question.title}`);
      console.log(`   回答数: ${question.answer_count}, 关注数: ${question.follower_count}`);
      console.log(`   链接: https://www.zhihu.com/question/${question.id}`);
    });
    
    return hotQuestions;
  } catch (error) {
    console.error('获取话题热门问题失败:', error);
    return [];
  }
}

// 使用示例: 获取"人工智能"话题下的热门问题
getHotQuestionsInTopic('19554796', 5);

用户回答数据分析

// 分析用户回答数据
async function analyzeUserAnswers(userId) {
  try {
    // 获取用户基本信息
    const user = await zhihu.user.profile(userId);
    console.log(`分析用户: ${user.name} (${user.id})`);
    
    // 获取用户回答列表
    const answers = await zhihu.user.answers(userId, { limit: 20 });
    console.log(`共获取到 ${answers.length} 条回答\n`);
    
    // 数据分析
    const stats = {
      totalLikes: 0,
      totalComments: 0,
      averageLikes: 0,
      topAnswer: null
    };
    
    answers.forEach(answer => {
      stats.totalLikes += answer.voteup_count;
      stats.totalComments += answer.comment_count;
      
      // 记录获赞最多的回答
      if (!stats.topAnswer || answer.voteup_count > stats.topAnswer.voteup_count) {
        stats.topAnswer = answer;
      }
    });
    
    stats.averageLikes = (stats.totalLikes / answers.length).toFixed(1);
    
    // 输出分析结果
    console.log('数据分析结果:');
    console.log(`总获赞数: ${stats.totalLikes}`);
    console.log(`总评论数: ${stats.totalComments}`);
    console.log(`平均获赞数: ${stats.averageLikes}`);
    
    if (stats.topAnswer) {
      console.log(`\n最受欢迎回答:`);
      console.log(`问题: ${stats.topAnswer.question.title}`);
      console.log(`获赞数: ${stats.topAnswer.voteup_count}`);
      console.log(`评论数: ${stats.topAnswer.comment_count}`);
    }
    
    return stats;
  } catch (error) {
    console.error('用户回答数据分析失败:', error);
    return null;
  }
}

// 使用示例
analyzeUserAnswers('用户ID');

⚠️ 注意事项与最佳实践

必要的授权配置

  • 必须设置 Cookie:使用前必须配置有效的知乎 Cookie,包含 z_c0(授权令牌)和 _xsrf
  • Cookie 获取方法:登录知乎网页版,通过浏览器开发者工具获取
  • 定期更新 Cookie:知乎 Cookie 有有效期,过期后需要重新获取

请求频率控制

  • 避免过于频繁的请求,建议添加合理的请求间隔
  • 大量数据获取时,实现分批获取和错误重试机制
  • 尊重知乎的服务条款,不要进行恶意爬取

💡 常见问题与解决方案

Q: 为什么请求总是返回 401 错误?

A: 这通常是由于 Cookie 配置不正确或已过期导致的。请检查你的 Cookie 设置,确保包含有效的 z_c0_xsrf 值。

Q: 如何处理请求频率限制?

A: 可以实现请求重试机制,并在重试时增加延迟:

// 带重试机制的请求函数
async function requestWithRetry(apiCall, retries = 3, delay = 1000) {
  try {
    return await apiCall();
  } catch (error) {
    if (retries > 0 && error.statusCode === 429) {
      console.log(`请求频率限制,${retries}次重试机会,等待${delay}ms...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return requestWithRetry(apiCall, retries - 1, delay * 2); // 指数退避策略
    }
    throw error;
  }
}

// 使用示例
requestWithRetry(() => zhihu.user.profile('用户ID'))
  .then(profile => console.log(profile))
  .catch(error => console.error(error));

Q: 如何获取更多数据?

A: 大多数列表接口支持分页参数,你可以通过分页获取更多数据:

// 分页获取用户回答
async function getAllUserAnswers(userId, batchSize = 20) {
  let allAnswers = [];
  let offset = 0;
  let hasMore = true;
  
  while (hasMore) {
    try {
      const answers = await zhihu.user.answers(userId, { limit: batchSize, offset });
      if (answers.length === 0) break;
      
      allAnswers = allAnswers.concat(answers);
      offset += batchSize;
      
      console.log(`已获取 ${allAnswers.length} 条回答,继续获取...`);
      await new Promise(resolve => setTimeout(resolve, 1000)); // 避免请求过快
    } catch (error) {
      console.error('获取回答失败:', error);
      hasMore = false;
    }
  }
  
  console.log(`共获取到 ${allAnswers.length} 条回答`);
  return allAnswers;
}

📚 项目结构与扩展

核心模块介绍

  • lib/api/: 包含主要 API 实现,如 user.js, question.js, answer.js 等
  • lib/parser/: 数据解析工具,负责将原始数据转换为结构化信息
  • lib/request.js: 请求处理模块,负责与知乎服务器通信
  • lib/urls.js: 知乎 API URL 管理

自定义扩展建议

  • 可以基于此项目开发数据存储模块,将获取的数据保存到数据库
  • 实现数据可视化功能,直观展示知乎平台的各类数据
  • 开发定时任务,定期获取和更新感兴趣的数据

📝 使用许可与注意事项

本项目采用 MIT 许可证开源,但请注意:

  • 这是非官方 API,使用时需遵守知乎的服务条款
  • 不要将此工具用于任何违反知乎规定的行为
  • 合理控制请求频率,避免给知乎服务器带来不必要的负担
  • 项目作者不对因使用本工具可能导致的任何账号问题负责

通过 zhihu-api,你可以轻松地与知乎平台进行交互,发掘有价值的数据。无论是学术研究、数据分析还是应用开发,这个工具都能为你提供有力的支持。开始你的知乎数据探索之旅吧!

登录后查看全文
热门项目推荐
相关项目推荐