Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python

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?

like image 978
JohnnyW Avatar asked Jan 29 '14 16:01

JohnnyW


People also ask

How do I open a HTML file using Beautifulsoup?

html" page = open(url) soup = BeautifulSoup(page. read()), and it works.


1 Answers

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) 
like image 67
falsetru Avatar answered Sep 17 '22 17:09

falsetru