将 Gmail 转换为 PDF:在 HTML 中嵌入图像

Ale*_*ont 5 python mime gmail-api

我正在使用 Gmail API 下载电子邮件。当这些电子邮件是 HTML 时,我尝试使用 Python 的 pdfkit 将它们转换为 PDF。

这在许多情况下都有效,但在某些情况下,html 有效负载包含图像标签,如src=“cid:169abdc4ae2c4da871d2”.

这个“cid”标签似乎是指作为多部​​分电子邮件的一部分发送的图像,但这不能被 PDFkit 处理。错误是:

wkhtmltopdf reported an error:
Loading pages (1/6)
Error: Failed to load cid:169abf0d0cdfffb7aff2, with network status code 301 and http status code 0 - Protocol "cid" is unknown
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?有没有办法将我从 gmail 有效负载获得的 HTML 转换为具有适当图片源的标准 HTML?

小智 2

您可以使用w3lib 包中的“remove_tags”方法:

删除所有标签:

import w3lib.html
doc = '<div><p><b>This is a link:</b> <a href="http://www.example.com">example</a></p></div>'
w3lib.html.remove_tags(doc)
'This is a link: example'
Run Code Online (Sandbox Code Playgroud)

删除特定标签:

 w3lib.html.remove_tags(doc, which_ones=('a','b'))
'<div><p>This is a link: example</p></div>'
Run Code Online (Sandbox Code Playgroud)