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

如何用Bash脚本与Python实现Chrome标签页URL的CLI保存?

Chrome标签页URL保存方案适配

一、Chrome是否有类似recovery.jsonlz4的文件?

Chrome没有和Firefox recovery.jsonlz4完全对应的实时会话文件,但存在几个相关存储文件:

  • Current Session/Current Tabs:位于Chrome用户数据目录(Linux下通常为~/.config/google-chrome/Default/),是二进制格式文件,保存当前会话标签页信息,但Chrome运行时会锁定这些文件,无法直接读取;关闭Chrome后可读取,但此时已无法获取实时打开的标签页。
  • Session Storage:属于单个站点的存储,并非全局标签页列表,无法用于批量获取标签页URL。

因此依赖静态文件的方式无法实现Chrome运行时的实时标签页抓取,需要换用其他方案。

二、CLI环境下获取Chrome当前打开标签页URL的方法(无需Selenium/PyAutoGUI)

方法1:利用Chrome远程调试协议

Chrome支持远程调试接口,可通过CLI开启调试端口后,调用接口获取实时标签页数据:

  1. 启动Chrome并开启调试端口:
    如果Chrome未运行,直接用以下命令启动:
    google-chrome --remote-debugging-port=9222
    
    如果Chrome已运行,先终止进程再重启(会关闭现有会话):
    pkill chrome
    google-chrome --remote-debugging-port=9222 &
    sleep 5 # 等待Chrome完全启动
    
  2. 获取并保存标签页URL:
    需要安装jq用于JSON解析,然后执行:
    curl -s http://localhost:9222/json | jq -r '.[].url' > saved_urls.txt
    
    该命令会将所有当前打开的标签页URL写入saved_urls.txt。

方法2:适配现有脚本的Chrome保存逻辑

修改你的Bash脚本中save_pages函数,集成上述远程调试逻辑:

save_pages() {
    if [[ $1 == 'firefox' ]];then
        export opentabs=$(find ~/ -name "recovery.jsonlz4" -type f);
        export browser='firefox';
        python3 amanuensis.py
    elif [[ $1 == 'chrome' ]];then
        # 检查jq依赖
        if ! command -v jq &> /dev/null; then
            echo "jq is required for Chrome save feature. Installing..."
            sudo apt install jq -y
        fi
        # 检查调试端口是否可访问
        if ! curl -s http://localhost:9222/json &> /dev/null; then
            echo "Restarting Chrome with remote debugging enabled..."
            pkill chrome
            google-chrome --remote-debugging-port=9222 &
            sleep 5
        fi
        # 抓取并保存URL
        curl -s http://localhost:9222/json | jq -r '.[].url' > saved_urls.txt
        echo "Chrome tabs saved to saved_urls.txt"
    else
        echo "We don't have support for this browser yet."
        exit 1
    fi
}

方法3:备选(读取Chrome历史数据库,局限性大)

Chrome的History文件是SQLite数据库(路径~/.config/google-chrome/Default/History),但运行时会被锁定,需复制后读取:

# 复制数据库到临时目录
cp ~/.config/google-chrome/Default/History /tmp/chrome_history
# 查询最近访问的URL(包含已关闭标签页,仅作备选)
sqlite3 /tmp/chrome_history "SELECT url FROM urls ORDER BY last_visit_time DESC LIMIT 50;" > saved_urls.txt

该方法无法区分当前打开和已关闭的标签页,仅适合临时应急场景。

注意事项

  • 开启远程调试端口后,本地程序可访问Chrome调试接口,请勿在公共环境下使用,避免安全风险。
  • 若Chrome使用多用户配置,需调整--user-data-dir路径到对应用户目录(如~/.config/google-chrome/Profile 1/)。

内容的提问来源于stack exchange,提问作者Márcio Scotuzzi Jr.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 21:15:21