首页 > 解决方案 > 我需要在 Python 的帮助下生成并保存 JPG 格式的 html/css 代码输出

问题描述

我想在 python 的帮助下以 jpg 格式保存到由 html/css 代码生成的输出。在谷歌上搜索时,我发现我们可以使用 IPython.display.HTML 来实现这一点。但是这个库只适用于 Python 2.0,将来会被弃用,所以想用 Python 3.0 + 实现这一点,还需要将输出保存为 html+css 代码生成的 JPG 格式。任何人都可以帮忙,如何实现这一点? 下面是我能够在 python 中呈现 html 输出的代码。

    #rendering frontend
    
    from IPython.display import display, Image
    IPython.display.HTML(filename='/content/drive/MyDrive/Analysed/Task2/test_page.html')

其中,test_page.html 文件包含简单的 html css 代码。

<html>
<head>
<link rel="stylesheet" href="mystyle.css">
<title>Hello</title>
<style>
.t{width:100px;height:100px;background-color:green;}
.container{width:1000px;height:700px;border:1px solid black;}
</style>
</head>

<body>
<div class="container">
  <div class="t">
    <p>Hello , How's day ?</p>
  </div>
</div>
</body>
</html>

这是我用上面的代码得到的输出,我想用 python 保存在 jpg 中。 html+css 渲染输出

标签: pythonipython

解决方案


我不知道您正在运行哪个操作系统,但您可以imgkit这样做。
安装: pip3 install --user imgkit

用法

import imgkit
imgkit.from_file("input.html", "output.jpg")

请注意,wkhtmltopdf对于这种方法,您需要一个有效的安装。


推荐阅读