4 回答

TA貢獻1775條經驗 獲得超8個贊
您可以使用imgkit來執行此操作
import imgkit
imgkit.from_file('test.html', 'out.jpg')
或者您也可以使用 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

TA貢獻1811條經驗 獲得超6個贊
如果你不希望你的項目依賴于wkhtmltopdf,就像其他Python模塊使用的那樣,我推薦html2image。
您可以使用該命令獲取它。您的計算機上還應安裝Web瀏覽器(目前為Chrome/Chromium)。pip install html2image
安裝后,您可以截取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')
您還可以直接截取現有 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')
有關文檔和更多示例,可以查看項目的 GitHub 頁面。

TA貢獻1802條經驗 獲得超10個贊
渲染HTML網站的另一個非常有用的工具是無頭Chromium瀏覽器。
在javascript中,你會使用puppeteer api與它進行交互,但是有一個非官方的poppeteer python移植,叫做pyppeteer。
根據我對imgkit等python工具的經驗,Chromium解決方案在加載圖像或iFrame等外部資產時要可靠得多。
要使用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())

TA貢獻1864條經驗 獲得超6個贊
from html2image import Html2Image
hti = Html2Image()
with open('./test.html') as f:
hti.screenshot(f.read(), save_as='out.png')
添加回答
舉報