Open In App

How to make HTML files open in Chrome using Python?

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites: Webbrowser

HTML files contain Hypertext Markup Language (HTML), which is used to design and format the structure of a webpage. It is stored in a text format and contains tags that define the layout and content of the webpage. HTML files are widely used online and displayed in web browsers.

To preview HTML files, we make the use of browsers, like Google Chrome, Mozilla Firefox, Apple Safari etc. The task of creating and previewing HTML files can be automated with the help of python scripts.

Here are a few ways how we can open HTML files on chrome:

Method 1: Using os and webbrowser

The webbrowser module in python provides a high-level interface to allow displaying Web-based documents to users, and the os module provides a portable way of using operating system dependent functionalities (like reading or writing files, manipulating file paths etc.). So let’s see how a combination of these both can help us to open an HTML page in Chrome browser:

Function used: open_new_tab() function is used to open html file in a new tab of your default browser.

Syntax:

open_new_tab(filename)

Approach:

  • Import module
  • Open and Create file 
  • Add html code 
  • Write code to file
  • Close file
  • Open file in browser window

Example:

Python3




# creating and viewing the html files in python
  
import webbrowser
import os
  
# to open/create a new html file in the write mode
f = open('GFG.html', 'w')
  
# the html code which will go in the file GFG.html
html_template = """
<html>
<head></head>
<body>
<p>Geeks For Geeks</p>
  
</body>
</html>
"""
# writing the code into the file
f.write(html_template)
  
# close the file
f.close()
  
# 1st method how to open html files in chrome using
filename = 'file:///'+os.getcwd()+'/' + 'GFG.html'
webbrowser.open_new_tab(filename)


Output:

Method 2: Without using the ‘os’ module:

If the HTML file is in the same directory as that of the python script, then there is no need of defining the file path with the os module. We can simply run the html file in new browser using the given steps:

Approach

  • Create a html file that you want to open
  • In Python, Import module
  • Call html file using open_new_tab()

Example:

Python3




Import webbrowser
  
webbrowser.open_new_tab('GFG.html')


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads