使用Python的webbrowser模块调用已注册浏览器打开新窗口的问题
使用Python的webbrowser模块调用已注册浏览器打开新窗口的问题
嘿,我懂你碰到的这个麻烦——本来想让Chrome在新窗口打开链接,结果每次都挤在同一个窗口里,确实挺闹心的。
先看看你给出的代码:
webbrowser.register('Chrome', None, webbrowser.BackgroundBrowser(path)) webbrowser.get('Chrome').open(link, new=1) webbrowser.get('Chrome').open_new(link)
这里有几个可以调整的点,帮你解决新窗口无法打开的问题:
- 浏览器类选择问题:
BackgroundBrowser是为后台运行浏览器设计的,它对新窗口的支持并不稳定。建议换成webbrowser.Chrome类(需确保Python版本支持),同时要保证path指向Chrome的实际可执行文件(比如Windows下是chrome.exe,Mac是Google Chrome.app/Contents/MacOS/Google Chrome)。 - 参数取值问题:
new=1在部分浏览器中会被解析为打开新标签页而非新窗口,你可以试试new=2,这个参数值是强制要求打开新窗口的。 - 重复调用冲突:你连续调用了
open和open_new,这可能会导致浏览器行为混乱,建议只保留其中一个调用即可。
调整后的示例代码可以参考:
import webbrowser # 替换成你系统中Chrome的实际路径 chrome_path = r'C:\Program Files\Google\Chrome\Application\chrome.exe' # Windows示例 # chrome_path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' # Mac示例 webbrowser.register('chrome', None, webbrowser.Chrome(chrome_path)) browser = webbrowser.get('chrome') browser.open(link, new=2)
另外还要注意,Chrome自身的设置也可能影响这个行为——如果浏览器开启了“继续之前的会话”或者强制在同一窗口打开链接,即使代码指定了新窗口,也可能被浏览器设置覆盖。可以检查一下Chrome的默认启动行为,确保没有限制新窗口的打开。
备注:内容来源于stack exchange,提问作者blahahaaahahaa
相关产品推荐
相关产品推荐

