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

无需Selenium,Python如何访问chrome://页面并提取浏览器信息?

如何用Python跨平台获取Chrome版本及访问chrome://页面内容

问题背景

常规的requests/urllib库仅支持http(s)协议,访问chrome://这类Chrome自定义协议页面时会抛出InvalidSchema错误,因为它们无法识别Chrome的二进制文件及自定义协议规则。尝试用selenium打开chrome://settings/help时,driver.page_source也无法获取到版本信息;而Windows命令行获取版本的方案无法适配Mac和Linux。我们需要一套跨平台方案,既能获取Chrome版本,又能访问其他chrome://页面内容。


解决方案

1. 跨平台获取Chrome版本(无需浏览器界面)

直接调用Chrome二进制文件的--version参数,是最高效的跨平台版本获取方式:

import subprocess
import sys

def get_chrome_version():
    # 定义各平台Chrome默认安装路径
    chrome_paths = {
        'win32': [
            r'C:\Program Files\Google\Chrome\Application\chrome.exe',
            r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
        ],
        'darwin': [
            '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
        ],
        'linux': [
            '/usr/bin/google-chrome',
            '/usr/bin/chromium-browser'
        ]
    }
    
    platform = sys.platform
    for path in chrome_paths.get(platform, []):
        try:
            # 执行--version命令并捕获输出
            result = subprocess.run(
                [path, '--version'],
                capture_output=True,
                text=True,
                check=True
            )
            # 返回完整版本字符串(如"Google Chrome 111.0.5563.146")
            return result.stdout.strip()
        except (subprocess.CalledProcessError, FileNotFoundError):
            continue
    return "Chrome/Chromium未找到"

# 调用示例
print(get_chrome_version())

2. 访问chrome://页面内容(基于Chrome DevTools Protocol)

要获取chrome://页面的完整内容,需借助Chrome DevTools Protocol(CDP),绕过selenium对内部页面的DOM限制:

import json
import subprocess
import sys
import time
from websocket import create_connection

def get_chrome_cdp_url():
    # 启动带远程调试的Chrome实例
    chrome_paths = {
        'win32': [
            r'C:\Program Files\Google\Chrome\Application\chrome.exe',
            r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
        ],
        'darwin': [
            '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
        ],
        'linux': [
            '/usr/bin/google-chrome',
            '/usr/bin/chromium-browser'
        ]
    }
    
    platform = sys.platform
    for path in chrome_paths.get(platform, []):
        try:
            # 以无头模式启动,启用远程调试端口9222
            subprocess.Popen(
                [path, '--remote-debugging-port=9222', '--headless=new', '--disable-gpu'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            time.sleep(2)  # 等待Chrome启动
            # 获取CDP的WebSocket连接地址
            conn = create_connection("http://localhost:9222/json/version")
            ws_info = json.loads(conn.recv())
            conn.close()
            return ws_info['webSocketDebuggerUrl']
        except Exception:
            continue
    return None

def fetch_chrome_internal_page(url):
    ws_url = get_chrome_cdp_url()
    if not ws_url:
        return "无法启动带远程调试的Chrome实例"
    
    ws = create_connection(ws_url)
    # 发送导航命令到目标页面
    ws.send(json.dumps({
        "id": 1,
        "method": "Page.navigate",
        "params": {"url": url}
    }))
    ws.recv()  # 忽略导航响应
    time.sleep(1)  # 等待页面加载
    
    # 获取页面完整DOM结构
    ws.send(json.dumps({"id": 2, "method": "DOM.getDocument"}))
    dom_result = json.loads(ws.recv())
    
    # 递归提取页面文本内容(可按需修改为提取特定DOM节点)
    def extract_text(node):
        text = node.get('nodeValue', '')
        for child in node.get('children', []):
            text += extract_text(child)
        return text
    
    page_content = extract_text(dom_result['result']['root'])
    ws.close()
    return page_content

# 示例:获取chrome://settings/help的内容
print(fetch_chrome_internal_page('chrome://settings/help'))

注意:需要先安装依赖库:pip install websocket-client


关键说明

  • 版本获取方案兼容Chrome和Chromium,各平台输出格式略有差异但核心版本信息一致。
  • 使用CDP时,若9222端口被占用,可修改--remote-debugging-port参数更换端口。
  • 无头模式(--headless=new)可避免弹出浏览器窗口,适合后台运行场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:30:33