Search code examples
pythonpython-webbrowser

Why do I get "webbrowser.Error: could not locate runnable browser"?


I'm new to coding in python and I'm wondering if some one can explain why this code works on the second try but not on the first?

I was just trying to open a browser that was not the default one.

first try --> did not work

import webbrowser

url='https://www.mozilla.org'
webbrowser.register('firefox', None)
webbrowser.BackgroundBrowser("C:\\Program Files\\Mozilla Firefox\\firefox.exe")
webbrowser.get('firefox').open(url)
webbrowser.Error: could not locate runnable browser

Process finished with exit code 1

second try --> works

import webbrowser

url='https://www.mozilla.org'
webbrowser.register('firefox', None, webbrowser.BackgroundBrowser("C:\\Program Files\\Mozilla Firefox\\firefox.exe"))
webbrowser.get('firefox').open(url)
Process finished with exit code 0

Solution

  • Like you can see here, register tells Python where the webbrowser with the name "firefox" can be found. You have to pass an instance (BackgroundBrowser) or a constructor. In the first code snippet you pass None as the constructor, which is not a valid browser class, it can thus not find/create the browser and cannot register it. In the second snippet you pass your BackgroundBrowser instance and thus it can register this valid browser as "firefox" and you can run it later.

    The 5th line (webbrowser.BackgroundBrowser...) in the first snippet does basically nothing, you are supposed to give that as an argument to register like you do in the second snippet.