前言
前面我們對博客園的文章進行了爬取,結果比較令人滿意,可以一下子下載某個博主的所有文章了。但是,我們獲取的只有文章中的文本內容,並且是沒有排版的,看起來也比較費勁。。。
咋么辦的?一個比較好的方法是將文章的正文內容轉化成pdf,就不要考慮排版的事情了,看起來比較美觀,也不會丟失一些關鍵信息。
python中將html轉化為pdf的常用工具是Wkhtmltopdf工具包,在python環境下,pdfkit是這個工具包的封裝類。如何使用pdfkit以及如何配置呢?分如下幾個步驟。
1、下載wkhtmltopdf安裝包,並且安裝到電腦上,在系統Path變量中添加wkhtmltopdf的bin路徑,以便於pdfkit的調用。
下載地址:https://wkhtmltopdf.org/downloads.html
請根據自己的系統版本,選擇合適的安裝包。如果沒有裝C語言庫,建議選擇Windows下的第二種。
【插入圖片 pdf1】

2、在pycharm中安裝pdfkit庫,過程就不介紹啦,前面講過類似的內容。
3、在pycharm中安裝whtmltopdf庫。
這個和第一步中的安裝包是兩個東西,請區別開來。
用法簡介
對於簡單的任務來說,代碼很easy,比如:
import pdfkit
pdfkit.from_url('http://baidu.com','out.pdf')
pdfkit.from_file('test.html','out.pdf')
pdfkit.from_string('Hello!','out.pdf')
pdfkit包含的方法很少,主要用的就是這三個,我們簡單看一下每個函數的API:
from_ulr()
def from_url(url, output_path, options=None, toc=None, cover=None,
configuration=None, cover_first=False):
"""
Convert file of files from URLs to PDF document
:param url: url可以是某一個url也可以是url的列表,
:param output_path: 輸出pdf的路徑,如果設置為False意味着返回一個string
Returns: True on success
"""
r = PDFKit(url, 'url', options=options, toc=toc, cover=cover,
configuration=configuration, cover_first=cover_first)
return r.to_pdf(output_path)
from_file()
def from_file(input, output_path, options=None, toc=None, cover=None, css=None,
configuration=None, cover_first=False):
"""
Convert HTML file or files to PDF document
:param input: 輸入的內容可以是一個html文件,或者一個路徑的list,或者一個類文件對象
:param output_path: 輸出pdf的路徑,如果設置為False意味着返回一個string
Returns: True on success
"""
r = PDFKit(input, 'file', options=options, toc=toc, cover=cover, css=css,
configuration=configuration, cover_first=cover_first)
return r.to_pdf(output_path)
from_string()
def from_string(input, output_path, options=None, toc=None, cover=None, css=None,
configuration=None, cover_first=False):
#類似的,這里就不介紹了
r = PDFKit(input, 'string', options=options, toc=toc, cover=cover, css=css,
configuration=configuration, cover_first=cover_first)
return r.to_pdf(output_path)
舉幾個栗子
我們可以傳入列表:
pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf')
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')
我們可以將一個打開的文件對象傳進去:
with open('file.html') as f:
pdfkit.from_file(f, 'out.pdf')
如果我們想繼續操作pdf,可以將其讀取成一個變量,其實就是一個string變量。
# Use False instead of output path to save pdf to a variable
pdf = pdfkit.from_url('http://google.com', False)
指定pdf的格式
我們可以指定各種選項,就是上面三個方法中的options。
具體的設置可以參考https://wkhtmltopdf.org/usage/wkhtmltopdf.txt 里面的內容。
我們這里只舉個栗子:
options = {
'page-size': 'Letter',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'custom-header' : [
('Accept-Encoding', 'gzip')
]
'cookie': [
('cookie-name1', 'cookie-value1'),
('cookie-name2', 'cookie-value2'),
],
'no-outline': None
}
pdfkit.from_url('http://google.com', 'out.pdf', options=options)
默認的,pdfkit會show出所有的output,如果你不想使用,可以設置為quite:
options = {
'quiet': ''
}
pdfkit.from_url('google.com', 'out.pdf', options=options)
我們還可以傳入任何html標簽,比如:
body = """
<html>
<head>
<meta name="pdfkit-page-size" content="Legal"/>
<meta name="pdfkit-orientation" content="Landscape"/>
</head>
Hello World!
</html>
"""
pdfkit.from_string(body, 'out.pdf') #with --page-size=Legal and --orientation=Landscape
改進
有了上面的知識之后,我們大可以嘗試一下,如果將之前的save_file方法做一些改變,就能夠實現我們下載PDF的目標啦。
我們將方法名改成save_to_pdf,並且在get_body方法中直接返回str(div),而不是div.text。代碼如下:
def save_to_pdf(url):
'''
根據url,將文章保存到本地
:param url:
:return:
'''
title=get_title(url)
body=get_Body(url)
filename=author+'-'+title+'.pdf'
if '/' in filename:
filename=filename.replace('/','+')
if '\\' in filename:
filename=filename.replace('\\','+')
print(filename)
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'custom-header': [
('Accept-Encoding', 'gzip')
]
}
#本來直接調用pdfkid的from方法就可以了,但是由於我們的wkhtmltopdf安裝包有點問題,一直沒法搜到,所以只能用本辦法,直接配置了wk的地址
#尷尬了,主要是一直沒法下載到最新的wk,只能在網上down了舊版本的。有誰能下到的話發我一份。。。
config=pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
pdfkit.from_string(body,filename,options=options,configuration=config)
print('打印成功!')
【插入圖片,pdf2】

哈哈,成功了,下載了這么多pdf,回頭慢慢看就可以了。

