Can beautiful soup output be sent to browser?

依然范特西╮ 提交于 2020-01-14 19:07:56

问题


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.


回答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

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.



来源:https://stackoverflow.com/questions/25706214/can-beautiful-soup-output-be-sent-to-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!