OpenCLI 学习教程

OpenCLI 学习教程

目录

  1. 快速开始
  2. 安装配置
  3. 基础命令
  4. 平台使用示例
  5. AI Agent 集成
  6. 自定义适配器
  7. 进阶技巧
  8. 常见问题
  9. 最佳实践

一、快速开始

1.1 什么是 OpenCLI?

OpenCLI 是一个 AI 原生的 CLI 运行时,让你可以通过命令行操作浏览器:

# 获取 B 站热门视频
opencli bilibili hot --limit 5

# 查看知乎日报
opencli zhihu daily

# 获取 Twitter 热搜
opencli twitter trending

1.2 核心优势

  • 零配置登录:复用 Chrome 登录状态
  • 轻量高效:Extension 架构,内存占用极低
  • AI 友好:原生 MCP 集成

1.3 5 分钟上手

# 1. 安装 OpenCLI
npm install -g @jackwener/opencli

# 2. 安装 Chrome 扩展(见下一节)

# 3. 诊断连接
opencli doctor

# 4. 执行第一个命令
opencli bilibili hot --limit 5

二、安装配置

2.1 系统要求

要求 说明
Node.js 18.0+
Chrome 最新稳定版
操作系统 macOS / Linux / Windows

2.2 安装 OpenCLI

# 使用 npm
npm install -g @jackwener/opencli

# 使用 pnpm
pnpm add -g @jackwener/opencli

# 使用 yarn
yarn global add @jackwener/opencli

# 验证安装
opencli --version

2.3 安装 Chrome 扩展

方法一:Chrome Web Store(推荐)

  1. 打开 Chrome Web Store
  2. 搜索 "OpenCLI"
  3. 点击"添加到 Chrome"

方法二:手动安装

# 1. 下载扩展
# 从 GitHub Releases 下载 opencli-extension.zip

# 2. 解压
unzip opencli-extension.zip -d opencli-extension

# 3. 加载到 Chrome
# - 打开 chrome://extensions/
# - 开启「开发者模式」
# - 点击「加载已解压的扩展程序」
# - 选择解压后的目录

2.4 验证安装

# 诊断连接状态
opencli doctor

# 预期输出:
# ✓ Chrome Extension connected
# ✓ Daemon running
# ✓ All systems operational

2.5 配置环境变量(可选)

# ~/.zshrc 或 ~/.bashrc

# Daemon 端口
export OPENCLI_DAEMON_PORT=9527

# 日志级别
export OPENCLI_LOG_LEVEL=info

# 配置文件路径
export OPENCLI_CONFIG_DIR=~/.opencli

三、基础命令

3.1 查看帮助

# 查看所有命令
opencli list

# 查看特定平台命令
opencli bilibili --help

# YAML 格式输出
opencli list -f yaml

3.2 通用参数

参数 说明 示例
--limit 限制返回数量 --limit 10
--json JSON 格式输出 --json
--format 自定义输出格式 --format yaml
--verbose 详细日志 -v

3.3 诊断命令

# 检查连接状态
opencli doctor

# 查看版本
opencli version

# 查看配置
opencli config

3.4 MCP 服务器

# 启动 MCP 服务器(供 AI Agent 调用)
opencli mcp

# 指定端口
opencli mcp --port 3000

四、平台使用示例

4.1 Bilibili(B 站)

# 获取热门视频
opencli bilibili hot --limit 10

# 搜索视频
opencli bilibili search "AI 教程"

# 获取用户信息
opencli bilibili user 嘉然今天吃什么

# 获取视频详情
opencli bilibili video BV1xx411c7mD

# 获取评论
opencli bilibili comments BV1xx411c7mD --limit 20

4.2 知乎

# 获取知乎日报
opencli zhihu daily

# 获取热榜
opencli zhihu hot

# 搜索问题
opencli zhihu search "如何学习编程"

# 获取问题详情
opencli zhihu question 12345678

# 获取回答
opencli zhihu answers 12345678 --limit 10

4.3 小红书

# 获取推荐
opencli xiaohongshu feed

# 搜索笔记
opencli xiaohongshu search "穿搭"

# 获取用户笔记
opencli xiaohongshu user 用户ID

4.4 Twitter/X

# 获取热搜
opencli twitter trending

# 搜索推文
opencli twitter search "AI"

# 获取用户推文
opencli twitter user elonmusk --limit 10

# 获取推文详情
opencli twitter tweet 1234567890

4.5 YouTube

# 获取热门
opencli youtube trending

# 搜索视频
opencli youtube search "tutorial"

# 获取视频信息
opencli youtube video dQw4w9WgXcQ

# 获取评论
opencli youtube comments dQw4w9WgXcQ

4.6 Reddit

# 获取热门
opencli reddit hot

# 获取子版块内容
opencli reddit r/programming

# 搜索
opencli reddit search "open source"

4.7 GitHub

# 获取趋势仓库
opencli github trending

# 搜索仓库
opencli github search "react"

# 获取仓库信息
opencli github repo facebook/react

# 获取 Issues
opencli github issues facebook/react --limit 10

4.8 微博

# 获取热搜
opencli weibo trending

# 获取用户微博
opencli weibo user 用户ID

# 搜索
opencli weibo search "今日热点"

五、AI Agent 集成

5.1 Claude Code 集成

在 Claude Code 的 MCP 配置中添加 OpenCLI:

// ~/.claude/claude_desktop_config.json
{
  "mcpServers": {
    "opencli": {
      "command": "opencli",
      "args": ["mcp"]
    }
  }
}

5.2 Cursor 集成

// .cursor/mcp.json
{
  "mcpServers": {
    "opencli": {
      "command": "opencli",
      "args": ["mcp"]
    }
  }
}

5.3 使用示例

配置完成后,AI Agent 可以直接调用:

用户提问

"帮我看看 B 站今天有什么热门视频"

AI 自动执行

opencli bilibili hot --limit 10

用户提问

"知乎上关于 AI 的热门话题有哪些?"

AI 自动执行

opencli zhihu search "AI" --limit 5

5.4 MCP 工具列表

通过 MCP 集成,AI 可以访问以下工具:

工具 功能
opencli_list 列出所有可用命令
opencli_execute 执行指定命令
opencli_search 跨平台搜索

六、自定义适配器

6.1 YAML 声明式适配器

适用场景:简单的页面抓取

创建步骤

# 1. 创建适配器目录
mkdir -p ~/.opencli/adapters/mysite

# 2. 创建配置文件
cat > ~/.opencli/adapters/mysite/adapter.yaml << 'EOF'
name: mysite
description: My Custom Site Adapter
version: 1.0.0
base_url: https://mysite.com

commands:
  - name: hot
    description: Get hot posts
    path: /hot
    selectors:
      items: ".post-item"
      title: ".post-title"
      link: "a"
      score: ".score"
    output:
      type: array
      fields:
        - title
        - link
        - score

  - name: search
    description: Search posts
    path: /search?q={query}
    params:
      - name: query
        required: true
    selectors:
      items: ".search-result"
      title: ".title"
      snippet: ".snippet"
EOF

# 3. 测试适配器
opencli mysite hot

6.2 TypeScript 注入适配器

适用场景:复杂的交互逻辑

创建步骤

# 1. 初始化项目
mkdir my-opencli-adapter
cd my-opencli-adapter
npm init -y

# 2. 安装依赖
npm install @jackwener/opencli typescript

# 3. 创建适配器
cat > src/adapter.ts << 'EOF'
import { Adapter, Command, Param } from '@jackwener/opencli';

export class MySiteAdapter extends Adapter {
  name = 'mysite';
  description = 'My Custom Site Adapter';

  @Command({
    name: 'hot',
    description: 'Get hot posts'
  })
  async getHot(
    @Param({ name: 'limit', description: 'Number of posts', default: 10 })
    limit: number
  ) {
    const page = await this.getPage();
    await page.goto('https://mysite.com/hot');

    // 等待加载
    await page.waitForSelector('.post-item');

    // 提取数据
    const posts = await page.evaluate(() => {
      return Array.from(document.querySelectorAll('.post-item'))
        .slice(0, limit)
        .map(el => ({
          title: el.querySelector('.title')?.textContent?.trim(),
          link: el.querySelector('a')?.href,
          score: parseInt(el.querySelector('.score')?.textContent || '0'),
        }));
    });

    return posts;
  }

  @Command({
    name: 'search',
    description: 'Search posts'
  })
  async search(
    @Param({ name: 'query', description: 'Search query', required: true })
    query: string,
    @Param({ name: 'limit', default: 10 })
    limit: number
  ) {
    const page = await this.getPage();
    await page.goto(`https://mysite.com/search?q=${encodeURIComponent(query)}`);

    await page.waitForSelector('.search-result');

    const results = await page.evaluate(() => {
      return Array.from(document.querySelectorAll('.search-result'))
        .slice(0, limit)
        .map(el => ({
          title: el.querySelector('.title')?.textContent?.trim(),
          snippet: el.querySelector('.snippet')?.textContent?.trim(),
          link: el.querySelector('a')?.href,
        }));
    });

    return results;
  }

  @Command({
    name: 'post',
    description: 'Create a new post'
  })
  async createPost(
    @Param({ name: 'title', required: true })
    title: string,
    @Param({ name: 'content', required: true })
    content: string
  ) {
    const page = await this.getPage();

    // 导航到创建页面
    await page.goto('https://mysite.com/create');
    await page.waitForSelector('#title');

    // 填写表单
    await page.type('#title', title);
    await page.type('#content', content);

    // 提交
    await page.click('button[type="submit"]');

    // 等待成功
    await page.waitForSelector('.success-message');

    return { success: true, title };
  }
}

export default MySiteAdapter;
EOF

# 4. 编译
npx tsc

# 5. 注册适配器
opencli adapter add ./dist/adapter.js

6.3 适配器配置参考

YAML 完整配置示例

name: example
version: 1.0.0
description: Example adapter

# 基础 URL
base_url: https://example.com

# 请求头
headers:
  User-Agent: "Mozilla/5.0..."
  Accept: "text/html"

# Cookie 处理
cookies:
  preserve: true  # 保留登录状态

# 命令定义
commands:
  # 简单抓取命令
  - name: list
    description: List items
    path: /api/items
    method: GET
    selectors:
      items: "$.data[*]"  # JSONPath
      id: "$.id"
      name: "$.name"

  # 带参数的命令
  - name: search
    description: Search items
    path: /search?q={query}&page={page}
    params:
      - name: query
        required: true
        type: string
      - name: page
        default: 1
        type: number
    selectors:
      items: ".result-item"
      title: ".title"

  # POST 请求
  - name: create
    description: Create item
    path: /api/items
    method: POST
    body:
      name: "{name}"
      content: "{content}"
    params:
      - name: name
        required: true
      - name: content
        required: true

# 输出配置
output:
  default_format: table
  formats:
    - table
    - json
    - yaml

七、进阶技巧

7.1 链式操作

# 使用 jq 处理输出
opencli bilibili hot --json | jq '.[] | .title'

# 导出为 CSV
opencli zhihu hot --json | jq -r '.[] | [.title, .url] | @csv' > hot.csv

# 批量操作
for tag in "AI" "React" "Python"; do
  opencli bilibili search "$tag" --limit 5 --json >> results.json
done

7.2 定时任务

# 使用 cron 定时采集
# crontab -e

# 每小时获取热搜
0 * * * * opencli weibo trending --json >> ~/logs/weibo_$(date +\%Y\%m\%d).json

# 每天早上获取知乎日报
0 8 * * * opencli zhihu daily

7.3 脚本集成

#!/bin/bash
# monitor.sh - 跨平台热度监控

echo "=== Daily Hot Monitor ==="
echo "Date: $(date)"
echo ""

echo "## Bilibili Hot"
opencli bilibili hot --limit 5

echo ""
echo "## Zhihu Hot"
opencli zhihu hot --limit 5

echo ""
echo "## Weibo Trending"
opencli weibo trending --limit 5

7.4 错误处理

#!/bin/bash
# 带错误处理的脚本

# 检查连接
if ! opencli doctor &> /dev/null; then
  echo "Error: OpenCLI not connected"
  exit 1
fi

# 执行命令并处理错误
result=$(opencli bilibili hot --limit 10 2>&1)
if [ $? -ne 0 ]; then
  echo "Command failed: $result"
  exit 1
fi

echo "$result"

7.5 调试模式

# 启用详细日志
OPENCLI_LOG_LEVEL=debug opencli bilibili hot

# 保存日志
opencli bilibili hot --verbose 2>&1 | tee debug.log

# 查看 Daemon 状态
opencli doctor --verbose

八、常见问题

8.1 连接问题

问题opencli doctor 显示连接失败

解决方案

# 1. 检查 Chrome 是否运行
pgrep -f "Google Chrome"

# 2. 检查扩展是否安装
# 打开 chrome://extensions/ 确认

# 3. 重启 Daemon
opencli daemon restart

# 4. 检查端口占用
lsof -i :9527

8.2 登录状态问题

问题:提示需要登录

解决方案

# 1. 确保在 Chrome 中已登录目标网站
# 2. 检查 Chrome 中的 Cookie
# 3. 尝试重新登录网站

8.3 适配器问题

问题:某个平台的命令不工作

解决方案

# 1. 检查适配器版本
opencli adapter list

# 2. 更新适配器
opencli adapter update bilibili

# 3. 使用调试模式
OPENCLI_LOG_LEVEL=debug opencli bilibili hot

8.4 性能问题

问题:命令执行缓慢

解决方案

# 1. 减少返回数量
opencli bilibili hot --limit 5

# 2. 使用 --json 跳过格式化
opencli bilibili hot --json

# 3. 检查网络连接

8.5 MCP 集成问题

问题:AI 无法调用 OpenCLI

解决方案

# 1. 确认 MCP 服务运行
opencli mcp &

# 2. 检查配置文件路径
# Claude Code: ~/.claude/claude_desktop_config.json
# Cursor: .cursor/mcp.json

# 3. 重启 AI 工具

九、最佳实践

9.1 安全建议

  1. 不要在公共电脑使用:OpenCLI 可以访问你的登录状态
  2. 定期检查权限:审查 Extension 的权限设置
  3. 敏感操作确认:对删除、发布等操作添加二次确认

9.2 性能优化

  1. 合理使用 limit:避免一次性获取过多数据
  2. 批量操作:合并多个请求
  3. 缓存数据:对频繁访问的数据进行缓存

9.3 开发建议

  1. 版本控制:将自定义适配器纳入 Git 管理
  2. 测试覆盖:为适配器编写测试用例
  3. 文档完善:记录适配器的使用说明

9.4 运维建议

  1. 监控日志:定期检查 OpenCLI 日志
  2. 定时更新:保持 OpenCLI 和适配器最新
  3. 备份配置:定期备份 ~/.opencli 目录

十、速查表

10.1 常用命令

命令 说明
opencli list 列出所有命令
opencli doctor 诊断连接
opencli mcp 启动 MCP 服务
opencli <platform> hot 获取热门内容
opencli <platform> search <query> 搜索内容

10.2 平台速查

平台 命令前缀 示例
Bilibili bilibili opencli bilibili hot
知乎 zhihu opencli zhihu daily
小红书 xiaohongshu opencli xiaohongshu feed
Twitter twitter opencli twitter trending
YouTube youtube opencli youtube search
Reddit reddit opencli reddit hot
GitHub github opencli github trending
微博 weibo opencli weibo trending

10.3 输出格式

参数 说明
--json JSON 格式
--yaml YAML 格式
--table 表格格式(默认)

参考资源

  • GitHub 仓库:https://github.com/jackwener/opencli
  • NPM 包:https://www.npmjs.com/package/@jackwener/opencli
  • 问题反馈:GitHub Issues

教程生成时间:2026-03-21