Windows平台下用Python获取Chrome标签页URL并实现指定URL重定向
Windows下Chrome标签页URL获取与重定向的Python实现
一、获取已打开的Chrome标签页URL
我们可以利用Chrome的远程调试协议(Remote Debugging Protocol),通过WebSocket连接到Chrome的调试端口来实时获取标签页信息。
步骤1:开启Chrome远程调试
右键Chrome快捷方式,选择「属性」,在「目标」栏末尾添加 --remote-debugging-port=9222(注意前面加空格),点击「确定」后重启Chrome。
步骤2:Python代码实现获取URL
先安装依赖包:
pip install websocket-client requests
编写脚本:
import requests import json def get_chrome_tabs(): # 获取Chrome调试端点列表 resp = requests.get("http://localhost:9222/json") tabs = resp.json() # 过滤出普通页面标签(排除背景页、扩展页等) return [{"id": tab["id"], "url": tab["url"], "title": tab["title"]} for tab in tabs if tab["type"] == "page"] if __name__ == "__main__": tabs = get_chrome_tabs() print("当前Chrome打开的标签页:") for tab in tabs: print(f"标题: {tab['title']} | URL: {tab['url']}")
运行脚本后,即可输出所有已打开标签页的URL和标题。
二、重定向特定URL(如google.com转bing.com)
基于获取到的标签页信息,我们可以通过远程调试协议发送导航指令,让符合条件的标签页跳转到目标地址。
扩展代码实现重定向
在上述代码基础上添加重定向逻辑:
import websocket import json def redirect_tab(tab_id, target_url): # 建立WebSocket连接到目标标签页的调试端点 ws_url = f"ws://localhost:9222/devtools/page/{tab_id}" ws = websocket.create_connection(ws_url) # 发送页面导航指令 navigate_cmd = json.dumps({ "id": 1, "method": "Page.navigate", "params": {"url": target_url} }) ws.send(navigate_cmd) # 接收响应(可忽略) ws.recv() ws.close() if __name__ == "__main__": tabs = get_chrome_tabs() for tab in tabs: if "google.com" in tab["url"]: print(f"重定向标签页: {tab['title']} -> https://www.bing.com") redirect_tab(tab["id"], "https://www.bing.com")
额外说明
- 这段代码会遍历所有标签页,只要URL包含
google.com,就自动跳转到必应首页。 - 如果需要持续监控新打开的标签页,可添加循环逻辑,每隔几秒重新获取标签列表并检查。
注意事项
- 确保9222端口未被其他程序占用,Chrome必须开启远程调试模式后再运行脚本。
- 若Chrome为多用户模式,需确认调试端口对应当前使用的用户进程。
内容的提问来源于stack exchange,提问作者Fakhreddine
相关产品推荐
相关产品推荐

