2017-02-26 52 views
1

我刚刚下载一个网站,蟒蛇在存储器中的HTML文件pdfkit

p =urllib2.build_opener(urllib2.HTTPCookieProcessor).open('http://www.google.com') 
html_content = p.read() 

,现在我想将其写入到一个PDF文件:

pdfkit.from_file(??????,'test.pdf') 

但是我怎么打发html_content在函数中? 它期望一个文件,但我不想将该文件首先保存为html。有没有办法在pdfkit.from_file函数中传递抓取的html_content?

注意:我不想使用.from_url,我首先要使用urllib2获取页面。

回答

1

pdfkit.from_string

.... 
html_content = p.read() 
pdfkit.from_string(html_content,'test.pdf') 

pdfkit.from_url

pdfkit.from_url('http://www.google.com') 

而且,pdfkit.from_file读取文件名作为第一个参数,它也接受类文件对象;您可以传递urllib....open的返回值,因为它是一个类似文件的对象。

参见pdfkit usage

+0

但它看起来像from_string,不解释html ...它只是想将文本写入pdf? – Bosiwow

+0

将p作为文件传递不起作用(它创建了一个空白pdf),但是,from_string确实解释了该字符串,并创建了一个很好的pdf!谢谢! – Bosiwow

相关问题