【问题标题】:In Python, how to open a string representing HTML in the browser?在 Python 中,如何在浏览器中打开代表 HTML 的字符串?
【发布时间】:2018-09-13 07:28:10
【问题描述】:

我想在浏览器中查看 Django 模板。这个特定的模板在render_to_string 中调用,但没有连接到视图,所以我不能只是runserver 并导航到我的localhost 的URL。

我的想法是在 Django shell 中简单地调用 render_to_string 并以某种方式将生成的字符串传递给 Web 浏览器(例如 Chrome)来查看它。但是,据我所知,webbrowser 模块仅接受 url 参数,不能用于呈现表示 HTML 的字符串。

知道如何实现这一目标吗?

【问题讨论】:

  • 为什么不能为此创建一个视图?

标签: python django python-webbrowser


【解决方案1】:

使用Data URL:

import base64

html = "..."

url = "text/html;base64," + base64.b64encode(html)
webbrowser.open(url)

【讨论】:

  • 我在复制这个 sn-p 时遇到了一些麻烦; base64.encode() 似乎需要两个参数,inputoutput。你的意思是b64encode()?后者还返回一个字节字符串,它不能简单地“添加”到 Python 3 中的常规字符串中。
  • 对不起,我是凭记忆写的,当然我弄错了。应该是b64encode,我更新了答案
【解决方案2】:

Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python 之后,我编写了一个测试用例,其中我将 HTML 写入一个临时文件并使用 file:// 前缀将其转换为 url 接受的 webbrowser.open()

import tempfile
import webbrowser
from django.test import SimpleTestCase
from django.template.loader import render_to_string


class ViewEmailTemplate(SimpleTestCase):
    def test_view_email_template(self):
        html = render_to_string('ebay/activate_to_family.html')
        fh, path = tempfile.mkstemp(suffix='.html')
        url = 'file://' + path

        with open(path, 'w') as fp:
            fp.write(html)
        webbrowser.open(url)

(不幸的是,我发现该页面不包含 Django 的 static 标签引用的图像,但这是一个单独的问题)。

【讨论】:

    【解决方案3】:

    您可以将 html 字符串转换为 url:

    https://docs.python.org/2/howto/urllib2.html

    【讨论】:

      猜你喜欢
      • 2018-01-29
      • 1970-01-01
      • 2023-03-26
      • 2017-04-15
      • 1970-01-01
      • 2019-04-12
      • 2012-06-30
      • 1970-01-01
      • 2014-04-07
      相关资源
      最近更新 更多