4

我正在尝试注册 Firefox 浏览器以在 Windows 上运行。根据 Webbrowser 的文档,“如果环境变量 BROWSER 存在,它被解释为覆盖浏览器的平台默认列表,作为 os.pathsep 分隔的浏览器列表按顺序尝试”。我有以下内容:

import os
import webbrowser
from subprocess import call

os.environ["BROWSER"] = "C:\\FirefoxPortable\\FirefoxPortable.exe"
webbrowser.open('http://google.com')

这仍然会打开 iexplorer(默认浏览器)。

还:

>>> webbrowser._browsers
{'windows-default': [<class 'webbrowser.WindowsDefault'>, None], 'c:\\program files\\internet explorer\\iexplore.exe': [None, <webbrowser.BackgroundBrowser object at 0x04A18F90>]}
>>> webbrowser._tryorder
['windows-default', 'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']

我如何在这里使用 Firefox?

资源:

# OK, now that we know what the default preference orders for each
# platform are, allow user to override them with the BROWSER variable.
if "BROWSER" in os.environ:
    _userchoices = os.environ["BROWSER"].split(os.pathsep)
    _userchoices.reverse()

    # Treat choices in same way as if passed into get() but do register
    # and prepend to _tryorder
    for cmdline in _userchoices:
        if cmdline != '':
            cmd = _synthesize(cmdline, -1)
            if cmd[1] is None:
                register(cmdline, None, GenericBrowser(cmdline), -1)
    cmdline = None # to make del work if _userchoices was empty
    del cmdline
    del _userchoices

# what to do if _tryorder is now empty?
4

2 回答 2

5

尝试了您的示例并得到了相同的结果:在 IE 中打开,而不是在 Firefox 中。原因是,在导入时webbrowserBROWSER环境变量尚未设置。通过简单地重新排序:

import os
# put it **before** importing webbroser
os.environ["BROWSER"] = "C:\\FirefoxPortable\\FirefoxPortable.exe"
import webbrowser
# from subprocess import call

webbrowser.open('http://google.com')

现在可以了。我通过尝试在命令行上设置环境变量来解决这个问题。注意:引号中的路径不起作用

set BROWSER=C:\FirefoxPortable\FirefoxPortable.exe

工作了,

set BROWSER="C:\FirefoxPortable\FirefoxPortable.exe"

没有。很抱歉回答迟了,但诊断

>>> webbrowser._browsers
>>> webbrowser._tryorder

非常有帮助,谢谢。

于 2015-09-01T10:54:50.540 回答
2

试试下面的代码:

webbrowser.register('firefox', None, webbrowser.GenericBrowser('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'))
a=webbrowser.get('firefox')
a.open("www.google.com")­­­­­
于 2015-05-27T13:43:09.717 回答