使用 Python 将 HTML 转换为 IMAGE

Man*_* __ 16 html python file file-conversion type-conversion

这是一个变量html_str,它是一个包含 html 标签和正文内容的字符串。我在 python 中使用以下代码从这个字符串创建了一个.html文件。

html_file = open("filename.html", "w")
html_file.write(html_str)
html_file.close()
Run Code Online (Sandbox Code Playgroud)

现在我得到了一个名为“ filename.html ”的html 文件。现在我想将该“filename.html”转换为一个名为 filename.jpg的图像,其中包含 html 文件的确切内容。请帮我。

小智 28

如果您不希望您的项目像其他 Python 模块一样依赖 wkhtmltopdf ,我推荐html2image

您可以使用pip install html2image命令来获取它。您的计算机上还应安装网络浏览器(目前为 Chrome/Chromium 或 Edge)。

安装后,您可以截取 HTML字符串的屏幕截图,如下所示:

from html2image import Html2Image
hti = Html2Image()

html = '<h1> A title </h1> Some text.'
css = 'body {background: red;}'

# screenshot an HTML string (css is optional)
hti.screenshot(html_str=html, css_str=css, save_as='page.png')
Run Code Online (Sandbox Code Playgroud)

您还可以直接截取现有 HTML文件URL的屏幕截图:

# screenshot an HTML file
hti.screenshot(
    html_file='page.html', css_file='style.css', save_as='page2.png'
)

# screenshot an URL
hti.screenshot(url='https://www.python.org', save_as='python_org.png')
Run Code Online (Sandbox Code Playgroud)

有关文档和更多示例,您可以查看该项目的 GitHub 页面

  • Html2Image 确实是 Chrome/Chromium 的包装器,并且具有生成图像的优点,这些图像(大多数时候)是您在自己的浏览器中看到的内容的完美复制品,而使用 wkhtmltopdf 并不总是如此。作为这个包的作者,感谢您的推荐,我希望将来添加对其他浏览器/工具的支持。 (9认同)

Moh*_*del 17

你可以通过使用imgkit来做到这一点

import imgkit

imgkit.from_file('test.html', 'out.jpg')
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用htmlcsstoimage Api

# pip3 install requests
import requests

HCTI_API_ENDPOINT = "https://hcti.io/v1/image"
HCTI_API_USER_ID = 'your-user-id'
HCTI_API_KEY = 'your-api-key'

data = { 'html': "<div class='box'>Hello, world!</div>",
         'css': ".box { color: white; background-color: #0f79b9; padding: 10px; font-family: Roboto }",
         'google_fonts': "Roboto" }

image = requests.post(url = HCTI_API_ENDPOINT, data = data, auth=(HCTI_API_USER_ID, HCTI_API_KEY))

print("Your image URL is: %s"%image.json()['url'])
# https://hcti.io/v1/image/7ed741b8-f012-431e-8282-7eedb9910b32
Run Code Online (Sandbox Code Playgroud)


Mer*_*ury 6

渲染 HTML 站点的另一个非常有用的工具是无头 Chromium 浏览器。

在 javascript 中,您可以使用 puppeteer api 与之交互,但是 puppeteer 有一个非官方的 python 端口,称为pyppeteer

根据我使用imgkit等 Python 工具的经验,在加载图像或 iFrame 等外部资源时,Chromium 解决方案要可靠得多。

要使用 pyppeteer 获取渲染 HTML 的图像版本,您只需加载页面,然后制作完整页面屏幕截图:

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('http://example.com')
    await page.screenshot({'path': 'example.png', 'fullPage': 'true'})
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)