简体   繁体   中英

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

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.")

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')

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM