如何用Python编写跨PC通用代码保存Chrome当前标签页URL?
跨平台Chrome当前标签页保存Python脚本
实现思路
针对不同操作系统,采用对应平台的原生方式精准获取Chrome当前打开的标签页:
- Windows:通过UI自动化遍历Chrome窗口控件,提取标签标题与URL
- macOS:调用AppleScript查询Chrome标签页数据
- Linux:通过DBus接口与Chrome进程通信获取标签信息
完整代码
import os import subprocess import sys from datetime import datetime def save_tabs(tabs, filename=None): """将标签页信息保存到本地文件""" if not filename: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"chrome_saved_tabs_{timestamp}.txt" with open(filename, "w", encoding="utf-8") as f: for idx, (title, url) in enumerate(tabs, 1): f.write(f"{idx}. {title}\n{url}\n\n") print(f"标签页已保存至:{os.path.abspath(filename)}") def get_chrome_tabs_windows(): """Windows平台获取Chrome标签页""" try: import uiautomation as auto except ImportError: print("请先安装依赖:pip install uiautomation") sys.exit(1) tabs = [] # 枚举所有Chrome窗口 chrome_windows = auto.WindowControl(searchDepth=1, ClassName="Chrome_WidgetWin_1") for window in chrome_windows.GetChildren(): if not window.Name: continue # 定位标签栏 tab_bar = window.Control(searchDepth=3, ClassName="Chrome_TabStrip") if not tab_bar.Exists(): continue # 记录当前激活的标签,避免操作后切换位置 current_tab = tab_bar.GetFirstChildControl(lambda c: c.IsActive) current_tab_idx = None for idx, tab in enumerate(tab_bar.GetChildren()): if tab == current_tab: current_tab_idx = idx break # 遍历每个标签提取信息 for tab in tab_bar.GetChildren(): if tab.ControlType == auto.ControlType.TabItemControl: title = tab.Name tab.Click() # 定位地址栏获取URL address_bar = window.Control(searchDepth=4, ClassName="Chrome_OmniboxView") if address_bar.Exists(): url = address_bar.Name tabs.append((title, url)) # 切回原激活标签 if current_tab_idx is not None: tab_bar.GetChildren()[current_tab_idx].Click() return tabs def get_chrome_tabs_macos(): """macOS平台获取Chrome标签页""" script = ''' tell application "Google Chrome" set tabList to {} repeat with w in windows repeat with t in tabs of w set end of tabList to (title of t as string) & "|||" & (URL of t as string) end repeat end repeat return tabList end tell ''' result = subprocess.run(["osascript", "-e", script], capture_output=True, text=True) if result.returncode != 0: print("获取标签页失败:", result.stderr) return [] tabs = [] for item in result.stdout.strip().split(","): if "|||" in item: title, url = item.split("|||", 1) tabs.append((title.strip(), url.strip())) return tabs def get_chrome_tabs_linux(): """Linux平台获取Chrome标签页""" # 先尝试Chromium的DBus路径 script = ''' dbus-send --session --print-reply=literal --dest=org.chromium.Chromium /org/chromium/Chromium org.chromium.Chromium.GetAllTabs ''' result = subprocess.run(script, shell=True, capture_output=True, text=True) # 失败则尝试Google Chrome的路径 if result.returncode != 0: script = ''' dbus-send --session --print-reply=literal --dest=org.google.chrome /org/google/chrome org.google.chrome.GetAllTabs ''' result = subprocess.run(script, shell=True, capture_output=True, text=True) if result.returncode != 0: print("获取标签页失败:请确保Chrome正在运行,且DBus服务正常") return [] tabs = [] # 解析DBus返回的结构化数据 parts = result.stdout.strip().split() i = 0 while i < len(parts): if len(parts) >= i+4: title = parts[i+2].strip('"') url = parts[i+3].strip('"') tabs.append((title, url)) i += 4 return tabs def main(): if sys.platform.startswith("win"): tabs = get_chrome_tabs_windows() elif sys.platform.startswith("darwin"): tabs = get_chrome_tabs_macos() elif sys.platform.startswith("linux"): tabs = get_chrome_tabs_linux() else: print("不支持当前操作系统") sys.exit(1) if not tabs: print("未检测到任何打开的Chrome标签页") return save_tabs(tabs) if __name__ == "__main__": main()
使用说明
- Windows平台:
- 执行前需安装依赖:
pip install uiautomation - 确保Chrome窗口未最小化,脚本需通过UI控件读取标签信息
- 执行前需安装依赖:
- macOS平台:
- 首次运行可能需要授权终端访问控制权限,在「系统设置-隐私与安全性-辅助功能」中允许终端或Python程序
- Linux平台:
- 确保Chrome已启动,且DBus服务正常运行
- 部分发行版需先安装
dbus-x11包
内容的提问来源于stack exchange,提问作者Mahmoud Soroor
相关产品推荐
相关产品推荐

