【问题标题】:Can beautiful soup output be sent to browser?美丽的汤输出可以发送到浏览器吗?
【发布时间】:2014-10-31 14:34:59
【问题描述】:

我对最近引入的 python 还很陌生,但是我对 php 的大部分经验。 php 在处理 HTML 时要做的一件事(毫不奇怪)是 echo 语句将 HTML 输出到浏览器。这使您可以使用内置的浏览器开发工具,例如 firebug。使用漂亮汤等工具时,有没有办法将输出 python/django 从命令行重新路由到浏览器?理想情况下,每次运行代码都会打开一个新的浏览器选项卡。

【问题讨论】:

    标签: python html browser beautifulsoup html-parsing


    【解决方案1】:

    如果你使用的是Django,可以在视图中renderBeautifulSoup的输出:

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

    其中dataBeautifulSoup 的HTML 输出。


    另一种选择是使用 Python 的 Basic HTTP server 并提供您拥有的 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 格式)打开它。

    另见其他选项:

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2016-09-26
      • 1970-01-01
      • 2013-09-30
      • 2023-04-03
      • 2016-12-18
      相关资源
      最近更新 更多