打开Firefox的问题

时间:2010-12-23 09:39:34

标签: python firefox browser

我正在尝试编写一个Python脚本来打开一个URL,但是当我尝试使用它时,我一直收到错误:

import webbrowser

firefox = webbrowser.get('mozilla')

这是错误:

Traceback (most recent call last):
  File "C:\Users\Gelu\Documents\CSCI\Image URL Generator\src\Generator.py", line 8, in <module>
    firefox = webbrowser.get('mozilla')
  File "C:\Program Files\Python31\lib\webbrowser.py", line 53, in get
    raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser

为什么这不起作用?

5 个答案:

答案 0 :(得分:17)

如果你这样做

import webbrowser
print webbrowser._browsers

您将获得系统中已识别浏览器的列表。

答案 1 :(得分:8)

我认为您正在尝试打开Firefox,对吧?

firefox = webbrowser.get('firefox')

作品。来自docs,浏览器类型。

答案 2 :(得分:6)

对我来说问题是,webbrowser.py无法识别我的Windows机器中的任何其他浏览器。因此,我必须注册浏览器,然后启动一个新选项卡。

import webbrowser
urL='https://www.google.com'
firefox_path="C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(firefox_path),1)
webbrowser.get('firefox').open_new_tab(urL)

希望这对某人有所帮助。

还有一些python笔记可以参考寄存器的作用,

webbrowser.register(name,constructor [,instance])¶

注册浏览器类型名称。注册浏览器类型后,get()函数可以返回该浏览器类型的控制器。如果未提供实例,或者为None,则将在不使用参数的情况下调用构造函数以在需要时创建实例。如果提供了实例,则构造函数永远不会被调用,并且可能是None。只有当您计划设置BROWSER变量或使用与您声明的处理程序的名称匹配的非空参数调用get()时,此入口点才有用。 / p>

答案 3 :(得分:0)

总结并为问题的未来搜索者的解决方案添加更多技巧:

  1. 如果您无法打开 Firefox 或收到错误“无法找到可运行的浏览器”(在 webbrowser.py 中),首先请检查 Python 是否看到任何浏览器(您应该获得浏览器列表,正如上面@Hugh Bothwell 所提到的,但对我来说,它只适用于 print

    的括号

    import webbrowser print (webbrowser._browsers)

  2. 如果没有 Firefox 或者你有一个空列表,你应该将浏览器的文件夹添加到系统路径(在这个例子中为 Firefox)(这个解决方案由@ntk4 here 给出)

Windows7 -> Start -> Control Panel -> System -> Advanced System Settings (on the left) -> pop-up window "System Properties" appears -> Advanced -> click on "Environment Variables" in the bottom right corner -> in the pop-up appeared in "System variables" field find "Path" and click on "Edit" button under the field -> in the end of the "Variable value" field add

;C:\Program Files\Mozilla Firefox\firefox.exe

->单击“确定”并在下一个窗口中应用(在您的机器或操作系统上可能有所不同)-> 重新启动您的笔记本电脑/PC

  1. 在 Python 中注册您的浏览器(由@Ali Moshiri here 回答)

    import webbrowser urL='https://www.python.org' mozilla_path="C:\Program Files\Mozilla Firefox\firefox.exe" webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path)) webbrowser.get('firefox').open_new_tab(urL)

这个魔法对我有用,最后我可以使用我想要的浏览器而不是默认浏览器:)

答案 4 :(得分:0)

我无法让 webbrowser 找到我的默认浏览器,这就是我修复它的方法

import webbrowser
    url = input("Enter Website Url: ")
    firefox_path = "C:\\Program Files\\Mozilla Firefox\\firefox.exe" #define the Path to firefox
    webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(firefox_path))
    webbrowser.get('firefox').open_new_tab(url)

基本上是这篇文章中已经给出的一个很好的答案的更新版本 这也可用于“google-chrome”,请参阅 webbrowser.register 下的 https://docs.python.org/3/library/webbrowser.html?highlight=webbrowser#module-webbrowser 以获取更多信息

相关问题