我一直在尝试使用 Weasyprint 和 PDFKIT 将网页转换为 pdf。我已成功保存了包含页面一部分的 PDF。在 weasyprint 中,我无法弄清楚如何从页面中获取正确的 CSS 样式。使用 PDFKIT 我似乎正在检索网站的移动版本而不是整个页面。我正在使用 python 3.6。
from urllib.request import Request, urlopen
import webbrowser
import pdfkit
import weasyprint
#pdfkit.from_url('http://google.com', 'out.pdf')
print("started script")
website = 'https://www.bbcgoodfood.com/recipes/3228/chilli-con-carne'
filename = 'savedPDF.pdf'
req = Request(website, headers={'User-Agent': 'Mozilla/5.0'})
print(urlopen(req).getcode())
temp = urlopen(req).getcode()
if temp == 200:
pdfkit.from_url(website, 'out.pdf')
weasyprint.HTML(website).write_pdf('/Users/me/Documents/weasyprint.pdf')
weasyprint.HTML(website).write_pdf(filename,stylesheets=[weasyprint.CSS('https://www.bbcgoodfood.com/sites/default/files/advagg_css/css__pDgD1vQBFL4LZ6AO_Uw8wEc3MBEaHOzbhMtPie685P8__Kxa0k0VBbKvV5-TOMN_kW3S7CrkFMM4Zf0LjDvzMFnk__mXPuNFBZ0nocZLk5Qifty02tMfg-gomArSBCcGw1mLo.css')])
我看不到 pdfkit 中的选项来指定要连接的内容。此外,从 weasyprint 创建的两个 PDF 是相同的。
在对上述包进行了相当长的一段时间后,我仍在努力实现正确的输出。
我已经解决了使用 webkit2png,这几乎完美无缺,唯一的缺点是我在一些保存的文件中出现了 cookie 弹出消息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句