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?
html" page = open(url) soup = BeautifulSoup(page. read()), and it works.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With