如何获取Edge浏览器所有已打开标签页的URL?含pywinauto实践问题
获取Edge浏览器所有标签页URL的解决方案
方法一:修正pywinauto控件定位
之前的代码找不到地址栏控件,是因为Edge的UI控件结构或定位逻辑有误。可以尝试切换到每个标签页后,通过自动化ID精准定位地址栏:
from pywinauto import Desktop desktop = Desktop(backend="uia") edge_window = desktop.windows(title_re=".*Microsoft Edge.*", control_type="Window")[0] # 获取所有标签页并遍历 tab_items = edge_window.descendants(control_type="TabItem") tab_urls = [] for tab in tab_items: # 切换到当前标签页 tab.click_input() # 通过自动化ID定位地址栏(Edge地址栏的固定auto_id为addressEdit) address_bar = edge_window.descendants(control_type="Edit", auto_id="addressEdit")[0] tab_urls.append(address_bar.get_value()) print(tab_urls)
注意:此方法需要Edge窗口处于前台,切换标签时会有界面闪烁,且依赖Edge的UI控件结构,版本更新后可能失效。
方法二:使用Edge DevTools Protocol(推荐)
通过浏览器原生的远程调试接口获取标签信息,无需依赖UI控件,稳定性更高:
- 配置Edge启动参数:右键Edge快捷方式,在「目标」栏末尾添加
--remote-debugging-port=9222,保存后重启Edge。 - 运行以下Python代码:
import json import urllib.request # 获取调试接口返回的标签数据 response = urllib.request.urlopen("http://localhost:9222/json") tabs_data = json.load(response) # 提取页面标签的标题和URL tab_info = [] for tab in tabs_data: if tab["type"] == "page": tab_info.append({ "title": tab["title"], "url": tab["url"] }) for info in tab_info: print(f"标题: {info['title']}, URL: {info['url']}")
此方法无需操作界面,后台即可获取所有标签页的对应信息,支持常规窗口和隐私窗口(隐私窗口需单独配置调试端口)。
方法三:使用Windows COM对象
通过Windows系统的Shell.Application组件获取Edge标签信息,适用于常规启动的Edge:
import win32com.client shell = win32com.client.Dispatch("Shell.Application") edge_tab_list = [] for window in shell.Windows(): # 过滤Edge进程窗口 if "msedge.exe" in window.FullName.lower(): edge_tab_list.append({ "title": window.LocationName, "url": window.LocationURL }) for tab in edge_tab_list: print(f"标题: {tab['title']}, URL: {tab['url']}")
注意:此方法无法获取隐私窗口的标签,且仅支持官方安装版Edge,便携版可能无法识别。
内容的提问来源于stack exchange,提问作者tomm
相关产品推荐
相关产品推荐

