Skip to content Skip to sidebar Skip to footer

Can Beautiful Soup Output Be Sent To Browser?

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)

Solution 1:

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

defmy_view(request):
    # some logic

    template = Template(data)
    context = Context({})  # you can provide a context if neededreturn 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 BeautifulSoupclassMyHandler(BaseHTTPRequestHandler):
    defdo_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(DATA)
        returntry:
    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):

enter image description here


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:

Hope that helps.

Post a Comment for "Can Beautiful Soup Output Be Sent To Browser?"