Can beautiful soup output be sent to browser?

beautifulsoup, browser, html, html-parsing, python

Solution

If it is Django you are using, you can render the output of `BeautifulSoup` in the view:

from django.http import HttpResponse
from django.template import Context, Template

def my_view(request):
    # some logic

    template = Template(data)
    context = Context({})  # you can provide a context if needed
    return HttpResponse(template.render(context))

where `data` is the HTML output from `BeautifulSoup`.

Another option would be to use Python's Basic HTTP server and serve the HTML you have:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

PORT_NUMBER = 8080
DATA = '<h1>test</h1>'  # supposed to come from BeautifulSoup

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(DATA)
        return


try:
    server = HTTPServer(('', PORT_NUMBER), MyHandler)
    print 'Started httpserver on port ', PORT_NUMBER
    server.serve_forever()
except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()

Another option would be to use `selenium`, open `about:blank` page and set the `body` tag's `innerHTML` appropriately. In other words, this would fire up a browser with the provided HTML content in the body:

from selenium import webdriver

driver = webdriver.Firefox()  # can be webdriver.Chrome()
driver.get("about:blank")

data = '<h1>test</h1>'  # supposed to come from BeautifulSoup
driver.execute_script('document.body.innerHTML = "{html}";'.format(html=data))

Screenshot (from Chrome):

And, you always have an option to save the `BeautifulSoup`'s output into an HTML file and open it using `webbrowser` module (using `file://..` url format).

See also other options at:

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

Hope that helps.

Problem

I'm pretty new to python having been introduced recently , but having most of my experience with php. One thing that php has going for it when working with HTML (not surprisingly) is that the echo statement outputs HTML to the browser. This lets you use the built in browser dev tools such as firebug. Is there a way to reroute output python/django from the command line to the browser when using tools such as beautiful soup? Ideally each run of the code would open a new browser tab.

Original source

Related problems