2017-02-26 22 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

相關問題