How to open HTML file in a browser with Python?

I am trying to open an HTML file from Python, but my script just displays the contents of the HTML file in Python instead of opening it in a browser. How can I fix this problem? How to open HTML file in Chrome browser?

testdata.html

<div>
    <a href="https://plot.ly/user001/2/" target="_blank" title="Success vs Failure" style="display: block; text-align: center;"><img src="https://plot.ly/~user001/2.png" alt="Success vs Failure" style="max-width: 100%;width: 600px;"  width="600" onerror="this.onerror=null;this.src='https://plot.ly/404.png';" /></a>
    <script data-plotly="user001:2"  src="https://plot.ly/embed.js" async></script>
</div>

Python 2.7 script:

import urllib
page =  urllib.urlopen('testdata.html').read()
print page
+4
source share
4 answers

Try specifying "file: //" at the beginning 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)
+5
source
import os
os.system("start [your's_url]")

Enjoy it!

+4
source

webbrowser :

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

Selenium.

, chromedriver.exe "C:\Python27\Scripts".

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("your page path")
print driver.page_source.encode('utf-8')
driver.quit()
display.stop()
+1

Source: https://habr.com/ru/post/1662503/


All Articles