Python 是否可以将漂亮的汤输出发送到浏览器?

Python 是否可以将漂亮的汤输出发送到浏览器?,python,html,browser,beautifulsoup,html-parsing,Python,Html,Browser,Beautifulsoup,Html Parsing,我最近才开始接触python,但我对php有着丰富的经验。php在处理HTML时所做的一件事(毫不奇怪)是echo语句将HTML输出到浏览器。这允许您使用内置的浏览器开发工具,如firebug。使用Beauty soup等工具时,是否有办法将输出python/django从命令行重新路由到浏览器?理想情况下,每次运行代码都会打开一个新的浏览器选项卡。如果您使用的是Django,则可以在视图中显示BeautifulSoup的输出: from django.http import HttpRespo

我最近才开始接触python,但我对php有着丰富的经验。php在处理HTML时所做的一件事(毫不奇怪)是echo语句将HTML输出到浏览器。这允许您使用内置的浏览器开发工具,如firebug。使用Beauty soup等工具时,是否有办法将输出python/django从命令行重新路由到浏览器?理想情况下,每次运行代码都会打开一个新的浏览器选项卡。

如果您使用的是Django,则可以在视图中显示
BeautifulSoup
的输出:

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))
其中,
data
是来自
BeautifulSoup
的HTML输出


另一种选择是使用Python并提供您拥有的HTML:

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()
屏幕截图(来自Chrome):


而且,您始终可以选择将
BeautifulSoup
的输出保存到HTML文件中,并使用模块(使用
file://..
url格式)

另请参见以下网址的其他选项:

希望有帮助

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))