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

如何在Linux系统下用Python无需Selenium或浏览器驱动获取当前浏览器URL

无需浏览器驱动获取Linux下主流浏览器当前URL的方案

在Linux下,确实有几种无需依赖Selenium或浏览器驱动的方式获取Chrome、Firefox、Brave等浏览器的当前URL,以下是针对不同浏览器的具体实现方案:

Chromium系浏览器(Chrome、Brave)

DBus接口调用

Linux下的Chromium、Chrome和Brave会暴露DBus接口,可直接通过Python调用获取标签信息。首先安装依赖库:

sudo apt-get install python3-dbus

示例代码:

import dbus

def get_chromium_browser_url():
    try:
        bus = dbus.SessionBus()
        # 遍历所有符合条件的DBus服务
        for service in bus.list_names():
            if any(keyword in service.lower() for keyword in ['chrome', 'brave', 'chromium']):
                try:
                    obj = bus.get_object(service, '/org/chromium/Browser')
                    iface = dbus.Interface(obj, 'org.chromium.Browser')
                    tabs = iface.GetTabs()
                    # 筛选活跃标签
                    for tab in tabs:
                        if tab.get('active'):
                            return tab['url']
                except dbus.DBusException:
                    continue
        return None
    except Exception as e:
        print(f"Error: {e}")
        return None

# 调用示例
current_url = get_chromium_browser_url()
print(current_url if current_url else "No active Chromium-based browser found")

注意事项

  • 部分老旧版本的Chromium系浏览器可能未开放该DBus接口,需确保浏览器版本较新。
  • 若浏览器以非默认用户数据目录启动,可能需要调整DBus服务的匹配逻辑。

Firefox浏览器

解析sessionstore.js文件

Firefox的会话信息存储在用户配置目录下的sessionstore.js文件中,可读取并解析该JSON文件获取当前活跃标签的URL。

示例代码:

import json
import os

def get_firefox_url():
    firefox_base_dir = os.path.expanduser('~/.mozilla/firefox')
    # 定位默认Profile目录
    profile_dir = None
    for dirname in os.listdir(firefox_base_dir):
        if dirname.endswith('.default') or dirname.endswith('.default-release'):
            profile_dir = os.path.join(firefox_base_dir, dirname)
            break
    if not profile_dir:
        return None
    
    session_path = os.path.join(profile_dir, 'sessionstore.js')
    if not os.path.exists(session_path):
        # 尝试读取备份文件
        backup_dir = os.path.join(profile_dir, 'sessionstore-backups')
        if os.path.exists(backup_dir):
            # 取最新的备份文件
            backups = sorted(os.listdir(backup_dir), key=lambda x: os.path.getmtime(os.path.join(backup_dir, x)))
            if backups:
                session_path = os.path.join(backup_dir, backups[-1])
        else:
            return None
    
    try:
        with open(session_path, 'r') as f:
            content = f.read()
            # 跳过开头的注释(部分版本的文件会有)
            if content.startswith('//'):
                content = content[2:]
            session_data = json.loads(content)
            # 找到选中的窗口和标签
            for window in session_data.get('windows', []):
                if window.get('selected'):
                    selected_tab_idx = window.get('selectedTab') - 1  # 索引从0开始
                    tabs = window.get('tabs', [])
                    if 0 <= selected_tab_idx < len(tabs):
                        entries = tabs[selected_tab_idx].get('entries', [])
                        if entries:
                            return entries[-1]['url']
        return None
    except Exception as e:
        print(f"Error: {e}")
        return None

# 调用示例
current_url = get_firefox_url()
print(current_url if current_url else "No active Firefox session found")

注意事项

  • Firefox运行时可能会锁定sessionstore.js,此时读取备份文件是更可靠的选择。
  • 不同Firefox版本的sessionstore.js结构可能略有差异,若解析失败需根据实际结构调整代码。

通用辅助:判断当前活跃浏览器

可以结合wmctrl工具获取当前活跃窗口对应的进程,再调用对应浏览器的URL获取方法。先安装依赖:

sudo apt-get install wmctrl

示例代码片段:

import subprocess

def get_active_browser():
    try:
        # 获取所有窗口信息,筛选活跃窗口
        win_output = subprocess.check_output(['wmctrl', '-l', '-p']).decode().splitlines()
        for line in win_output:
            parts = line.split()
            # 活跃窗口的desktop字段为当前桌面编号,这里简化判断为非空且进程ID有效
            if len(parts) >= 4:
                pid = parts[3]
                proc_name = subprocess.check_output(['ps', '-p', pid, '-o', 'comm=']).decode().strip().lower()
                if proc_name in ['chrome', 'brave-browser', 'chromium', 'firefox']:
                    return proc_name
        return None
    except Exception as e:
        print(f"Error: {e}")
        return None

# 结合上述方法使用
active_browser = get_active_browser()
if active_browser in ['chrome', 'brave-browser', 'chromium']:
    print(get_chromium_browser_url())
elif active_browser == 'firefox':
    print(get_firefox_url())
else:
    print("No supported browser is active")

方案对比

方案适用范围优势局限
Chromium系DBus接口Chrome、Brave、Chromium实时性强,无需解析文件依赖DBus,老旧版本不支持
Firefox sessionstore解析Firefox无额外依赖(除Python)可能遇文件锁定,版本兼容性需注意
窗口管理器进程判断所有支持的浏览器通用逻辑,自动匹配浏览器需要安装wmctrl,增加系统依赖

内容的提问来源于stack exchange,提问作者Guilherme Lourenço da Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:15:39