可以将美丽的汤输出发送到浏览器吗?

use*_*629 3 html python browser beautifulsoup html-parsing

我最近刚刚介绍了python的新手,但我拥有大部分的php经验.使用HTML时(不出意外),php支持的一件事是echo语句将HTML输出到浏览器.这使您可以使用内置的浏览器开发工具,如firebug.有没有办法在使用美丽的汤等工具时将输出python/django从命令行重新路由到浏览器?理想情况下,每次运行代码都会打开一个新的浏览器选项卡.

ale*_*cxe 5

如果是你正在使用的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))
Run Code Online (Sandbox Code Playgroud)

data来自的HTML输出在哪里BeautifulSoup.


另一种选择是使用Python的Basic HTTP服务器并提供您拥有的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()
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用selenium,打开about:blank页面并适当地设置body标签innerHTML.换句话说,这将启动一个浏览器,其中包含正文中提供的HTML内容:

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))
Run Code Online (Sandbox Code Playgroud)

屏幕截图(来自Chrome):

在此输入图像描述


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

另见其他选项:

希望有所帮助.