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

3 投票
1 回答
1817 浏览
提问于 2025-04-20 05:43

我最近刚接触Python,之前大部分时间都是在用PHP。PHP在处理HTML时有个很方便的地方,就是它的echo语句可以直接把HTML输出到浏览器。这让我们可以使用浏览器自带的开发者工具,比如firebug。那么,有没有办法把Python/Django的输出从命令行转到浏览器,特别是在使用像Beautiful Soup这样的工具时?理想情况下,每次运行代码时都能打开一个新的浏览器标签页。

1 个回答

6

如果你在使用Django框架,你可以在视图中将BeautifulSoup的输出进行render处理:

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的基本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()

还有一个选择是使用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))

截图(来自Chrome浏览器):

在这里输入图片描述


你也可以选择将BeautifulSoup的输出保存到一个HTML文件中,然后使用webbrowser模块打开它(使用file://..的URL格式)。

你还可以查看其他选项:

希望这些对你有帮助。

撰写回答