How to open a web browser from Python

This goes under the Tips and Tricks category. 

Also under Stuff I wish I had known about a long time ago.

The trick is in the standard library, in the webbrowser module.

For documentation of the webbrowser module,
import webbrowser
new = 2 # open in a new tab, if possible

# open a public URL, in this case, the webbrowser docs
url = "",new=new)

# open an HTML file on my own (Windows) computer
url = "file://X:/MiscDev/language_links.html",new=new)
This entry was posted in Python features. Bookmark the permalink.

4 Responses to How to open a web browser from Python

  1. Ilya says:

    I have several webbrowsers. How can I open a new tab in a browser that is not default browser?

  2. Brendan says:

    I usually manufacture a command “firefox –new-tab “+url

    Stop focus stealing on firefox:

    Set browser.tabs.loadDivertedInBackground to ‘true’ in about:config

  3. Steve says:

    I tried this, and it worked ok the first couple of times. But now it does this weird thing where it cuts off the filename of the file I am trying to open and sticks it on the end of the path. ie: if the file is in C:/python/test.html, the error message says, “Cannot find ‘file:///C:/pythonest.html. Make sure the path or Internet address is correct.” I’m sure the path is correct because I can open the file from the command line without any problems.

    • Steve Ferg says:

      I’m betting that this is a problem with the way the filename is being fed to Python. If you feed Python this string (a Windows filename)


      it is going to interpret “\p” and “\t” as escaped characters. It can’t do anything with “\p”, but “\t” will be interpreted as a tab character and either ignored or displayed in a way that you don’t expect. So “python\test.html” will become “python[TAB]est.html”.

Comments are closed.