Python 爬蟲(chóng):把廖雪峰教程轉(zhuǎn)換成 PDF 電子書(shū)

寫(xiě)爬蟲(chóng)似乎沒(méi)有比用 Python 更合適了,Python 社區(qū)提供的爬蟲(chóng)工具多得讓你眼花繚亂,各種拿來(lái)就可以直接用的 library 分分鐘就可以寫(xiě)出一個(gè)爬蟲(chóng)出來(lái),今天嘗試寫(xiě)一個(gè)爬蟲(chóng),將廖雪峰老師的 Python 教程爬下來(lái)做成 PDF 電子書(shū)方便離線(xiàn)閱讀。

開(kāi)始寫(xiě)爬蟲(chóng)前,我們先來(lái)分析一下網(wǎng)站的頁(yè)面結(jié)構(gòu),網(wǎng)頁(yè)的左側(cè)是教程的目錄大綱,每個(gè) URL 對(duì)應(yīng)到右邊的一篇文章,右側(cè)上方是文章的標(biāo)題,中間是文章的正文部分,正文內(nèi)容是我們關(guān)心的重點(diǎn),我們要爬的數(shù)據(jù)就是所有網(wǎng)頁(yè)的正文部分,下方是用戶(hù)的評(píng)論區(qū),評(píng)論區(qū)對(duì)我們沒(méi)什么用,所以可以忽略它。

crawer-view.png

工具準(zhǔn)備

弄清楚了網(wǎng)站的基本結(jié)構(gòu)后就可以開(kāi)始準(zhǔn)備爬蟲(chóng)所依賴(lài)的工具包了。requests、beautifulsoup 是爬蟲(chóng)兩大神器,reuqests 用于網(wǎng)絡(luò)請(qǐng)求,beautifusoup 用于操作 html 數(shù)據(jù)。有了這兩把梭子,干起活來(lái)利索,scrapy 這樣的爬蟲(chóng)框架我們就不用了,小程序派上它有點(diǎn)殺雞用牛刀的意思。此外,既然是把 html 文件轉(zhuǎn)為 pdf,那么也要有相應(yīng)的庫(kù)支持, wkhtmltopdf 就是一個(gè)非常好的工具,它可以用適用于多平臺(tái)的 html 到 pdf 的轉(zhuǎn)換,pdfkit 是 wkhtmltopdf 的Python封裝包。首先安裝好下面的依賴(lài)包,接著安裝 wkhtmltopdf

<pre style="box-sizing: border-box; overflow: auto; font-family: Consolas, monaco, monospace; font-size: 14px; display: block; padding: 20px 40px; margin: 20px 0px; line-height: 24px; color: rgb(255, 255, 255); word-break: break-all; word-wrap: break-word; background: rgb(51, 51, 51); border: none; border-radius: 0px; font-weight: 400;">pip install requests
pip install beautifulsoup4
pip install pdfkit
</pre>

安裝 wkhtmltopdf

Windows平臺(tái)直接在 wkhtmltopdf 官網(wǎng)下載穩(wěn)定版的進(jìn)行安裝,安裝完成之后把該程序的執(zhí)行路徑加入到系統(tǒng)環(huán)境 $PATH 變量中,否則 pdfkit 找不到 wkhtmltopdf 就出現(xiàn)錯(cuò)誤 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行進(jìn)行安裝

<pre style="box-sizing: border-box; overflow: auto; font-family: Consolas, monaco, monospace; font-size: 14px; display: block; padding: 20px 40px; margin: 20px 0px; line-height: 24px; color: rgb(255, 255, 255); word-break: break-all; word-wrap: break-word; background: rgb(51, 51, 51); border: none; border-radius: 0px; font-weight: 400;">$ sudo apt-get install wkhtmltopdf # ubuntu
$ sudo yum intsall wkhtmltopdf # centos
</pre>

爬蟲(chóng)實(shí)現(xiàn)

一切準(zhǔn)備就緒后就可以上代碼了,不過(guò)寫(xiě)代碼之前還是先整理一下思緒。程序的目的是要把所有 URL 對(duì)應(yīng)的 html 正文部分保存到本地,然后利用 pdfkit 把這些文件轉(zhuǎn)換成一個(gè) pdf 文件。我們把任務(wù)拆分一下,首先是把某一個(gè) URL 對(duì)應(yīng)的 html 正文保存到本地,然后找到所有的 URL 執(zhí)行相同的操作。

用 Chrome 瀏覽器找到頁(yè)面正文部分的標(biāo)簽,按 F12 找到正文對(duì)應(yīng)的 div 標(biāo)簽: <div class="x-wiki-content">,該 div 是網(wǎng)頁(yè)的正文內(nèi)容。用 requests 把整個(gè)頁(yè)面加載到本地后,就可以使用 beautifulsoup 操作 HTML 的 dom 元素 來(lái)提取正文內(nèi)容了。

body

具體的實(shí)現(xiàn)代碼如下:用 soup.find_all 函數(shù)找到正文標(biāo)簽,然后把正文部分的內(nèi)容保存到 a.html 文件中。

<pre style="box-sizing: border-box; overflow: auto; font-family: Consolas, monaco, monospace; font-size: 14px; display: block; padding: 20px 40px; margin: 20px 0px; line-height: 24px; color: rgb(255, 255, 255); word-break: break-all; word-wrap: break-word; background: rgb(51, 51, 51); border: none; border-radius: 0px; font-weight: 400;">def parse_url_to_html(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
body = soup.find_all(class_="x-wiki-content")[0]
html = str(body)
with open("a.html", 'wb') as f:
f.write(html)
</pre>

第二步就是把頁(yè)面左側(cè)所有 URL 解析出來(lái)。采用同樣的方式,找到 左側(cè)菜單標(biāo)簽 <ul class="uk-nav uk-nav-side">

dir

具體代碼實(shí)現(xiàn)邏輯:因?yàn)轫?yè)面上有兩個(gè)uk-nav uk-nav-side的 class 屬性,而真正的目錄列表是第二個(gè)。所有的 url 獲取了,url 轉(zhuǎn) html 的函數(shù)在第一步也寫(xiě)好了。

<pre style="box-sizing: border-box; overflow: auto; font-family: Consolas, monaco, monospace; font-size: 14px; display: block; padding: 20px 40px; margin: 20px 0px; line-height: 24px; color: rgb(255, 255, 255); word-break: break-all; word-wrap: break-word; background: rgb(51, 51, 51); border: none; border-radius: 0px; font-weight: 400;">def get_url_list():
"""
獲取所有URL目錄列表
"""
response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000")
soup = BeautifulSoup(response.content, "html.parser")
menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1]
urls = []
for li in menu_tag.find_all("li"):
url = "http://www.liaoxuefeng.com" + li.a.get('href')
urls.append(url)
return urls
</pre>

最后一步就是把 html 轉(zhuǎn)換成pdf文件了。轉(zhuǎn)換成 pdf 文件非常簡(jiǎn)單,因?yàn)?pdfkit 把所有的邏輯都封裝好了,你只需要調(diào)用函數(shù) pdfkit.from_file

<pre style="box-sizing: border-box; overflow: auto; font-family: Consolas, monaco, monospace; font-size: 14px; display: block; padding: 20px 40px; margin: 20px 0px; line-height: 24px; color: rgb(255, 255, 255); word-break: break-all; word-wrap: break-word; background: rgb(51, 51, 51); border: none; border-radius: 0px; font-weight: 400;">def save_pdf(htmls):
"""
把所有html文件轉(zhuǎn)換成pdf文件
"""
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'custom-header': [
('Accept-Encoding', 'gzip')
]
}
pdfkit.from_file(htmls, file_name, options=options)
</pre>

執(zhí)行 save_pdf 函數(shù),電子書(shū) pdf 文件就生成了,效果圖:

pdf

總結(jié)

總共代碼量加起來(lái)不到50行,不過(guò),且慢,其實(shí)上面給出的代碼省略了一些細(xì)節(jié),比如,如何獲取文章的標(biāo)題,正文內(nèi)容的 img 標(biāo)簽使用的是相對(duì)路徑,如果要想在 pdf 中正常顯示圖片就需要將相對(duì)路徑改為絕對(duì)路徑,還有保存下來(lái)的 html 臨時(shí)文件都要?jiǎng)h除,完整代碼放在github上。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容