如何在已有真实Chrome浏览器中启动Selenium或Puppeteer并打开新标签页
在已打开的Chrome窗口中打开新标签页的代码片段
没问题!要复用已经打开的Chrome窗口(带着你的书签、扩展程序)打开新标签,这里有两个实用的方案,看你的使用场景选:
方案1:直接调用系统Chrome(适合非测试场景)
用Python的webbrowser模块就能轻松实现,它会自动复用已有Chrome窗口打开新标签:
import webbrowser # 根据你的系统修改Chrome路径(如果系统默认Chrome可以省略这行,直接用webbrowser.open) chrome_path = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s' # Windows # chrome_path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome %s' # Mac # chrome_path = '/usr/bin/google-chrome %s' # Linux # new=2 表示在已有窗口打开新标签;new=1是新窗口,new=0是替换当前标签 webbrowser.get(chrome_path).open('https://www.example.com', new=2)
方案2:Selenium复用已有Chrome会话(适合测试场景)
如果是用Selenium做测试,需要先手动启动Chrome并开启远程调试,再用代码连接:
第一步:手动启动Chrome(带调试端口)
- Windows:按下Win+R,输入以下命令后回车:
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:/ChromeProfile" - Mac:打开终端,输入:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --user-data-dir="/Users/你的用户名/Library/Application Support/Google/Chrome" - Linux:终端输入:
google-chrome --remote-debugging-port=9222 --user-data-dir="$HOME/.config/google-chrome"
第二步:用Selenium连接并打开新标签
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() # 连接到刚才开启的调试端口 options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") # 连接已有Chrome会话 driver = webdriver.Chrome(options=options) # 执行JS打开新标签 driver.execute_script("window.open('https://www.example.com');")
这样就能在你日常使用的Chrome窗口(带所有书签、扩展)里打开新标签做测试啦!
内容的提问来源于stack exchange,提问作者Edward Dan
相关产品推荐
相关产品推荐

