How to open an HTML file in the browser from Python?

You can use webbrowser library:

import webbrowser
url = 'file:///path/to/your/file/testdata.html'
webbrowser.open(url, new=2)  # open in new tab

Try specifying the "file://" at the start of the URL.

// Also, use the absolute path of the file:

webbrowser.open('file://' + os.path.realpath(filename))

Or

import webbrowser
new = 2 # open in a new tab, if possible

// open a public URL, in this case, the webbrowser docs
url = "http://docs.python.org/library/webbrowser.html"
webbrowser.open(url,new=new)

// open an HTML file on my own (Windows) computer
url = "file://d/testdata.html"
webbrowser.open(url,new=new)

import os
os.system("start [your's_url]")

Enjoy!


Here's a way that doesn't require external libraries and that can work of local files as well.

import subprocess
import os

url = "https://stackoverflow.com"
# or a file on your computer
# url = "/Users/yourusername/Desktop/index.html
try: # should work on Windows
    os.startfile(url)
except AttributeError:
    try: # should work on MacOS and most linux versions
        subprocess.call(['open', url])
    except:
        print('Could not open URL')

Tags:

Python

Html