在Python中将HTML字符串转换为图像

18 投票
2 回答
61639 浏览
提问于 2025-04-16 15:34

我想在Python中把下面的HTML转换成PNG图片。

<html>
    <b>Bold text</b>
</html>

这个HTML当然是个例子。

我试过用'pisa',但是它是把HTML转换成PDF,而不是图片。我可以先把HTML转换成PDF,然后再把PDF转换成PNG,但我在想有没有什么直接的方法(也就是HTML直接变成PNG)。任何内置的或者外部的模块都可以。

如果可以用Graphicsmagick或者Imagemagick来实现,那就太完美了。

2 个回答

8

为了更详细地解释vartec的回答,下面是如何使用它的说明...

安装 webkit2png
最简单的方法可能就是直接从GitHub上克隆这个项目,然后运行设置。

mkdir python-webkit2png
git clone https://github.com/adamn/python-webkit2png.git python-webkit2png
python setup.py install

这需要你已经安装了python和git。如果你在cygwin环境下,这样做会把webkit2png添加为一个命令到你的路径中。我没有在其他终端或操作系统上测试过。

运行它
假设你的网站文件就在当前目录下。(我有一个使用了css样式表的html文件,但你不需要考虑css文件。)

webkit2png something.html -o something.png

选项
输入webkit2png -h可以告诉我们一些信息:

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -x WIDTH HEIGHT, --xvfb=WIDTH HEIGHT
                        Start an 'xvfb' instance with the given desktop size.
  -g WIDTH HEIGHT, --geometry=WIDTH HEIGHT
                        Geometry of the virtual browser window (0 means
                        'autodetect') [default: (0, 0)].
  -o FILE, --output=FILE
                        Write output to FILE instead of STDOUT.
  -f FORMAT, --format=FORMAT
                        Output image format [default: png]
  --scale=WIDTH HEIGHT  Scale the image to this size
  --aspect-ratio=RATIO  One of 'ignore', 'keep', 'crop' or 'expand' [default:
                        none]
  -F FEATURE, --feature=FEATURE
                        Enable additional Webkit features ('javascript',
                        'plugins')
  -c COOKIE, --cookie=COOKIE
                        Add this cookie. Use multiple times for more cookies.
                        Specification is value of a Set-Cookie HTTP response
                        header.
  -w SECONDS, --wait=SECONDS
                        Time to wait after loading before the screenshot is
                        taken [default: 0]
  -t SECONDS, --timeout=SECONDS
                        Time before the request will be canceled [default: 0]
  -W, --window          Grab whole window instead of frame (may be required
                        for plugins)
  -T, --transparent     Render output on a transparent background (Be sure to
                        have a transparent background defined in the html)
  --style=STYLE         Change the Qt look and feel to STYLE (e.G. 'windows').
  --encoded-url         Treat URL as url-encoded
  -d DISPLAY, --display=DISPLAY
                        Connect to X server at DISPLAY.
  --debug               Show debugging information.
  --log=LOGFILE         Select the log output file

值得注意的选项包括设置宽度和高度。

故障排除
在使用cygwin时,我遇到了webkit2png: cannot connect to X server :0.0的错误。要解决这个问题(我已经执行了export DISPLAY=0.0),我需要启动一个X-Server。在cygwin中,可以通过在第二个终端运行startxwin来实现。确保先通过cygwin的设置安装它。

13

webkit2png. 原版只适用于Mac电脑,但幸运的是,有一个可以在多个平台上使用的版本:https://github.com/AdamN/python-webkit2png

撰写回答