如何用Python读取Windows中已打开浏览器的标签页URL
获取Windows浏览器标签页URL的Python方案
浏览器进程不会将标签页URL直接暴露在进程参数中,因此需要通过读取浏览器内部存储文件或UI自动化两种方式实现需求。
方法一:读取浏览器SQLite数据库(支持Chrome/Edge/Firefox)
Chromium内核浏览器(Chrome、Edge)
- 数据库路径:
- Chrome:
C:\Users\<你的用户名>\AppData\Local\Google\Chrome\User Data\Default\History - Edge:
C:\Users\<你的用户名>\AppData\Local\Microsoft\Edge\User Data\Default\History
- Chrome:
- 注意:浏览器运行时会锁定数据库文件,必须先复制一份副本再读取。
- 代码示例:
import sqlite3 import shutil import os from datetime import datetime def get_chromium_tabs(browser_type="chrome"): # 确定数据库路径 user_profile = os.path.expanduser("~") if browser_type == "chrome": db_path = os.path.join(user_profile, "AppData", "Local", "Google", "Chrome", "User Data", "Default", "History") elif browser_type == "edge": db_path = os.path.join(user_profile, "AppData", "Local", "Microsoft", "Edge", "User Data", "Default", "History") else: return [] # 复制数据库到临时文件 temp_db = os.path.join(user_profile, "temp_history.db") try: shutil.copyfile(db_path, temp_db) except PermissionError: print("浏览器正在运行,无法直接读取数据库,请关闭浏览器重试,或使用UI自动化方法") return [] # 查询关联的标签页与URL信息 conn = sqlite3.connect(temp_db) cursor = conn.cursor() query = """ SELECT u.url, u.title, t.last_accessed FROM urls u JOIN tabs t ON u.id = t.url ORDER BY t.last_accessed DESC """ cursor.execute(query) tabs = [] for row in cursor.fetchall(): url, title, last_accessed = row # 转换Chromium微秒级时间戳为可读格式 access_time = datetime(1601, 1, 1) + datetime.timedelta(microseconds=last_accessed) tabs.append({ "url": url, "title": title, "last_accessed": access_time.strftime("%Y-%m-%d %H:%M:%S") }) conn.close() os.remove(temp_db) return tabs # 使用示例 chrome_tabs = get_chromium_tabs("chrome") print("Chrome标签页:") for tab in chrome_tabs: print(f"- {tab['title']}: {tab['url']}")
Firefox浏览器
- 数据库路径:
C:\Users\<你的用户名>\AppData\Roaming\Mozilla\Firefox\Profiles\<随机ID>.default-release\places.sqlite - 逻辑与Chromium类似,需先复制数据库副本,再通过
moz_places和moz_session_history表关联查询打开的标签页信息。
方法二:UI自动化(支持运行中的浏览器)
利用pywinauto库直接控制浏览器窗口,读取地址栏内容,无需关闭浏览器。
- 安装依赖:
pip install pywinauto - 代码示例(以Chrome为例):
from pywinauto import Desktop, Application def get_chrome_tabs_ui(): try: # 连接到Chrome进程 app = Application(backend="uia").connect(title_re=".*Chrome") # 获取主窗口 window = app.window(title_re=".*Chrome") # 获取标签页控件 tab_control = window.child_control(type_name="Tab") tabs = [] for i in range(tab_control.item_count()): # 切换到目标标签页 tab_control.select(i) # 读取地址栏内容 address_bar = window.child_control(auto_id="addressBar", control_type="Edit") url = address_bar.get_value() # 读取标签页标题 tab_title = tab_control.item_text(i) tabs.append({ "title": tab_title, "url": url }) return tabs except Exception as e: print(f"获取失败:{str(e)}") return [] # 使用示例 chrome_tabs = get_chrome_tabs_ui() print("Chrome标签页(UI自动化):") for tab in chrome_tabs: print(f"- {tab['title']}: {tab['url']}")
注意事项
- UI自动化要求浏览器窗口未被最小化,且控件结构未因浏览器版本更新改变
- 不同浏览器的控件ID可能不同,需根据实际情况调整定位逻辑
内容的提问来源于stack exchange,提问作者zacc
相关产品推荐
相关产品推荐

