如何用Python获取浏览器当前打开网站名称以完善应用时长追踪?
实现浏览器当前网站名称追踪的Python方案
核心思路
在现有应用时长统计逻辑基础上,当检测到活跃窗口为Chrome/Firefox时,通过窗口标题解析或浏览器调试协议提取当前活跃标签页的网站名称,替换原有的“Chrome/Firefox”应用标识,改为统计具体网站的使用时长。
方案1:基于窗口标题的轻量实现(快速落地、跨平台兼容)
Windows、macOS、Linux下,Chrome/Firefox的窗口标题默认格式为「网站名称 - 浏览器名称」,可直接通过获取当前活跃窗口标题提取网站名称。
依赖库安装
pip install pygetwindow psutil
代码示例
import pygetwindow as gw import psutil def get_active_browser_website(): active_window = gw.getActiveWindow() if not active_window: return None, None # 获取进程名称,判断是否为目标浏览器 pid = active_window._hWnd if hasattr(active_window, '_hWnd') else active_window.id try: process = psutil.Process(pid) process_name = process.name().lower() except: return None, None browser_name = None if 'chrome' in process_name: browser_name = 'Chrome' elif 'firefox' in process_name: browser_name = 'Firefox' else: return None, None # 解析窗口标题提取网站名称 window_title = active_window.title if browser_name in window_title: website_name = window_title.split(f' - {browser_name}')[0].strip() # 处理空白标签页等特殊情况 if not website_name: website_name = f"{browser_name} 空白标签页" return browser_name, website_name return browser_name, window_title
集成到现有统计逻辑
在你的定时检测循环中(比如每秒一次),调用上述函数替换原有应用统计逻辑:
import time from collections import defaultdict usage_stats = defaultdict(float) idle_time = 0.0 check_interval = 1.0 # 每秒检测一次 while True: # 执行现有系统闲置检测逻辑 is_idle = your_idle_check_function() if is_idle: idle_time += check_interval time.sleep(check_interval) continue # 获取当前活跃网站或应用 browser, website = get_active_browser_website() if website: usage_stats[website] += check_interval else: # 非浏览器应用,沿用原有应用名称获取逻辑 app_name = your_get_active_app_function() usage_stats[app_name] += check_interval time.sleep(check_interval)
方案2:基于浏览器调试协议的精准实现(适合需URL+标题的场景)
如果窗口标题解析存在格式异常(比如部分网站自定义标题包含浏览器名称),可通过Chrome DevTools Protocol(CDP)或Firefox远程调试API直接获取活跃标签页信息。
Chrome实现步骤
- 关闭所有Chrome实例,以调试模式启动:
chrome.exe --remote-debugging-port=9222
- Python代码获取活跃标签页:
import requests import json def get_chrome_active_website(): try: # 获取所有标签页信息 response = requests.get('http://localhost:9222/json') tabs = json.loads(response.text) # 筛选出活跃的页面标签 active_tab = next(tab for tab in tabs if tab['type'] == 'page' and tab['active']) return 'Chrome', active_tab['title'], active_tab['url'] except: return 'Chrome', 'Unknown', 'Unknown'
Firefox实现步骤
开启Firefox远程调试:
- 地址栏输入
about:config,设置devtools.debugger.remote-enabled和devtools.chrome.enabled为true - 启动Firefox时添加参数:
firefox.exe -start-debugger-server 6000
- 地址栏输入
Python代码(通过WebSocket连接):
import websocket import json def get_firefox_active_website(): ws = websocket.create_connection("ws://localhost:6000") # 发送获取标签页列表命令 ws.send(json.dumps({ "to": "root", "type": "listTabs" })) response = json.loads(ws.recv()) ws.close() # 筛选出选中的活跃标签 active_tab = next(tab for tab in response['tabs'] if tab['selected']) return 'Firefox', active_tab['title'], active_tab['url']
注意事项
- 窗口标题解析可能存在边缘场景,可添加正则匹配优化(比如用
re.split(r'\s-\s(Chrome|Firefox)$', window_title))。 - 调试协议方式需手动开启浏览器调试模式,若用于分发应用,需补充自动启动浏览器的逻辑。
- 跨平台适配:Linux可改用
wmctrl命令或gi.repository.Gdk获取窗口信息;macOS可改用pyobjc实现窗口标题提取。
内容的提问来源于stack exchange,提问作者Haripriya N
相关产品推荐
相关产品推荐

