Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python
beautifulsoup, html, python, python-3.x
Solution
Using `webbrowser.open`:
import os
import webbrowser
html = '<html> ... generated html string ...</html>'
path = os.path.abspath('temp.html')
url = 'file://' + path
with open(path, 'w') as f:
f.write(html)
webbrowser.open(url)
Alternative using `NamedTemporaryFile` (to make the file eventually deleted by OS):
import tempfile
import webbrowser
html = '<html> ... generated html string ...</html>'
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f:
url = 'file://' + f.name
f.write(html)
webbrowser.open(url)
Problem
I have used BeautifulSoup for Python 3.3 to successfully pull desired info from a web page. I have also used BeautifulSoup to generate new HTML code to display this info. Currently, my Python program prints out the HTML code, which I then have to copy, paste, and save as an HTML file, then from there, I can test it in a browser. So my question is this, is there a way in Python to launch the HTML code generated by BeautifulSoup in a web browser so that I don't have to go through the copy and paste method I use now?