python实现动态网页转图片

准备imgkit环境

使用系统是ubuntu 16

第一部分:

  • 首先是imgkt的安装:
pip install imgkit

然后是wkhtmltopdf的安装,不 要 使 用 a p t − g e t 安 装 ! ! 因 为 a p t − g e t 安 装 的 是 一 个 阉 割 版 ! \color{#FF3030}{不要使用 apt-get安装!!因为apt-get安装的是一个阉割版! }使aptgetaptget!在文档中有写道:

Warning! Version in debian/ubuntu repos have reduced functionality
(because it compiled without the wkhtmltopdf QT patches), such as
adding outlines, headers, footers, TOC etc. To use this options you
should install static binary from wkhtmltopdf site or you can use this
script.

正确的使用方式是创建 init.sh文件,将以下内容拷贝进去:

#!/usr/bin/env bash
sudo apt-get install -y openssl build-essential xorg libssl-dev xvfb
pip install coverage
wget https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar xf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
cd wkhtmltox
sudo chown root:root bin/wkhtmltopdf
sudo cp -r * /usr/

然后运行 bash init.sh 即可成功安装所有包。

第二部分:

关于imgkit不能读取中文内容,一般是缺少字体造成的。

首先下载SimSun.ttf文件 (在win10的C:\Windows\FontsSIMSUNB.TTF 复制出来改名为SimSun.ttf

然后把文件放到unbuntu系统的 /usr/share/fonts 目录下,刷新fc-cache -f -v。同时,在html文本的<head></head>标签下添加字体设置。

    <style>
        * {
            padding: 0;
            margin: 0;
            font-family: SimSun;
        }
    </style>
    <meta charset="UTF8">

如果表格需要居中就加:

<style>* {
        padding: 0;
        margin: 0;
        font-family: SimSun;
    }
    table {margin: auto;}
    body{text-align: center;}
    </style>
    <meta charset="UTF8">

将动态网页转化为图片

import imgkit

with open('res.html', errors='ignore') as html_file:
    imgkit.from_file(html_file, 'res.jpg')

版权声明:本文为weixin_43813300原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。