1

How do I open a local HTML file into a browser from a python file?

This is what I have so far. But I have read online that it will not work for local files? Is there a way around this?

My goal is to open the python file in the cli

then type the password

then if the password is correct

open the HTML file.

This is what I have so far but it won't open a local file:

import urllib.request
passer = "abcdef"
passwd_attempt = input("Type in the password please: ")

if passwd_attempt == passer:
    page = urllib.request.urlopen('test.html')
    text = page.read().decode("utf8")
    print(text)
else:
    print("Wrong password. Please try again.")
Kellen
  • 23
  • 1
  • 6
  • https://stackoverflow.com/questions/22445217/python-webbrowser-open-to-open-chrome-browser – Phix Oct 20 '20 at 02:24

2 Answers2

2

To read local html content use lxml.html and open():

from lxml import html
with open('test.html','r',encoding='utf-8') as f:
  text = html.fromstring(f.read())

To open in browser, I will use the webbrowser module instead and file:// before local path:

import webbrowser
webbrowser.open('file://test.html')
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Try to use subprocess command runner method, as you can open HTML file with the command line by typing "chrome path/to/htmlfile.html"

import subprocess

# in case chrome browser
subprocess.run(["chrome", "path/to/htmlfile.html"])
  • this is not a good idea. it needs to handle multiple exceptions and it is not robust in different environments. – prhmma Feb 18 '21 at 10:50