Python的Webbrowser模块永远不会在新窗口中打开链接

3
我想要自动化打开多个用户档案,根据给定的名字列表在几个不同的网站上,但我无法找到一种方法来在新窗口中打开链接,这意味着我不能将我打开的不同网站分类到它们自己的窗口集合中。
这是我的代码:
import webbrowser


chrome_path="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
firefox_path="C:\\Program Files\\Mozilla Firefox\\Firefox.exe"
strURL = "http://www.python.org"


webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path),1)
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(chrome_path),1)

webbrowser.open(strURL, new=0)
webbrowser.open(strURL, new=1)
webbrowser.open(strURL, new=2)
webbrowser.get('chrome').open(strURL)
webbrowser.get('firefox').open(strURL)
webbrowser.get('chrome').open_new(strURL)
webbrowser.get('firefox').open_new(strURL)

无论我给new(0、1或2)传递什么值,它都只会在我最后点击的窗口中打开一个新选项卡。我已经尝试了Python Web浏览器模块文档中找到的所有其他方法,但是每个人都只是建议使用“new=1”或webbrowser.open_new(),但这两者都不起作用。即使我将其指向火狐浏览器,它也只会在谷歌浏览器中打开。
P.S.
我找到了一个小的解决方法,但并不完全满意。
import webbrowser


chrome_path = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
chrome_path_NW = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s --new-window"
firefox_path = "C:\\Program Files\\Mozilla Firefox\\Firefox.exe"
strURL = "http://www.python.org"

controller = webbrowser.get(chrome_path)
controllerNW = webbrowser.get(chrome_path_NW)

controllerNW.open(strURL, new=0)
controller.open(strURL, new=1)
controller.open(strURL, new=2)
controller.open("www.youtube.com", new=2)

需要关注的重点是“chrome_path”变量。我已经更改了它,使其可以作为命令运行并接受参数。我在这里找到了一些用于Chromium的启动参数,并且似乎也适用于Chrome。“--new-window”将打开一个新窗口,然后我可以在该窗口中打开更多选项卡,但这是完全绕过Python模块的解决方法,我不确定在运行此脚本时是否会出现问题。如果有任何功能可以将链接分组在特定窗口中打开,那对我来说将更加有用。

1个回答

0

我知道这有点晚了,但希望未来能帮助到某些人。 基本上,您需要使用子进程模块在加载新网页之前打开一个新窗口。

import subprocess
import time
import webbrowser

subprocess.Popen('open -a /Applications/Google\ Chrome.app --new', shell=True)
time.sleep(0.5) # this is to let the app open before you try to load a new page
webbrowser.open(url)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接