如何用Python复制浏览器标签页链接?Chrome多标签页存文件方法
如何用Python获取并保存Chrome已打开标签页的链接
我来帮你解决这个问题,这里有几种可靠的方法来实现需求——不管是复制单个已打开标签页的链接,还是批量导出多个标签页的URL到文件:
方法一:使用Selenium连接已运行的Chrome(适合需要更多交互的场景)
这种方法可以让你直接控制已经打开的Chrome窗口,非常适合需要切换标签页、操作页面的场景。
步骤1:开启Chrome的远程调试模式
首先需要让Chrome允许远程连接:
- Windows:右键Chrome快捷方式 → 「属性」→ 在「目标」栏的末尾添加
--remote-debugging-port=9222(注意前面有空格),然后点击「应用」,重启Chrome。 - Mac:关闭所有Chrome窗口,打开终端运行:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 - Linux:关闭所有Chrome窗口,终端运行:
google-chrome --remote-debugging-port=9222
步骤2:编写Python代码
from selenium import webdriver from selenium.webdriver.chrome.options import Options import pyperclip # 配置Chrome选项,连接到已开启调试的端口 chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") # 初始化驱动(不会新开Chrome窗口,而是连接已运行的实例) driver = webdriver.Chrome(options=chrome_options) # --- 复制单个标签页链接到剪贴板 --- current_url = driver.current_url pyperclip.copy(current_url) print(f"当前激活标签页的链接已复制到剪贴板:{current_url}") # --- 批量导出所有标签页链接到文件 --- # 获取所有标签页的句柄 tab_handles = driver.window_handles tab_urls = [] # 遍历每个标签页,提取URL for handle in tab_handles: driver.switch_to.window(handle) tab_urls.append(driver.current_url) # 保存到文本文件 with open("chrome_tab_links.txt", "w", encoding="utf-8") as f: for url in tab_urls: f.write(f"{url}\n") print(f"已成功导出{len(tab_urls)}个标签页链接到chrome_tab_links.txt") # 断开连接(不会关闭原来的Chrome窗口) driver.quit()
方法二:直接调用Chrome DevTools API(轻量无依赖)
如果不需要页面交互,只是单纯导出链接,用这个方法更轻量,不需要安装Selenium,只需要requests库即可。
步骤1:同样开启Chrome的远程调试模式(和方法一的步骤1一致)
步骤2:编写Python代码
import requests import json # 获取所有标签页的信息 response = requests.get("http://127.0.0.1:9222/json") tabs_data = response.json() # 过滤出真正的标签页(排除背景页、扩展页等) tab_urls = [tab["url"] for tab in tabs_data if tab["type"] == "page"] # 保存到文件 with open("chrome_tab_links.txt", "w", encoding="utf-8") as f: for url in tab_urls: f.write(f"{url}\n") print(f"已成功导出{len(tab_urls)}个标签页链接到chrome_tab_links.txt") # 如果要复制单个激活标签页的链接 active_tab = next(tab for tab in tabs_data if tab["active"]) active_url = active_tab["url"] # 可选:用pyperclip复制到剪贴板(需要先安装pyperclip:pip install pyperclip) import pyperclip pyperclip.copy(active_url) print(f"当前激活标签页的链接已复制到剪贴板:{active_url}")
注意事项
- 确保开启远程调试时,没有其他Chrome实例在运行,否则可能会连接失败。
- 端口号(9222)可以自定义,但要保证不被其他程序占用。
- 如果使用Selenium,需要确保你的Chrome版本和ChromeDriver版本匹配(可以从Chrome设置→关于Chrome查看版本,然后下载对应版本的ChromeDriver)。
内容的提问来源于stack exchange,提问作者saidul islam
相关产品推荐
相关产品推荐

