1. 程式人生 > >【Python3.6】:廖雪峰python教程轉換成 PDF

【Python3.6】:廖雪峰python教程轉換成 PDF

開始寫爬蟲前,我們先來分析一下該網站https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000
的頁面結構,網頁的左側是教程的目錄大綱,每個 URL 對應到右邊的一篇文章,右側上方是文章的標題,中間是文章的正文部分,正文內容是我們關心的重點,我們要爬的資料就是所有網頁的正文部分,下方是使用者的評論區,評論區對我們沒什麼用,所以可以忽略它。

這裡寫圖片描述
工具準備

弄清楚了網站的基本結構後就可以開始準備爬蟲所依賴的工具包了。requests、beautifulsoup 是爬蟲兩大神器,reuqests 用於網路請求,beautifusoup 用於操作 html 資料。有了這兩把梭子,幹起活來利索,scrapy 這樣的爬蟲框架我們就不用了,小程式派上它有點殺雞用牛刀的意思。此外,既然是把 html 檔案轉為 pdf,那麼也要有相應的庫支援, wkhtmltopdf 就是一個非常好的工具,它可以用適用於多平臺的 html 到 pdf 的轉換,pdfkit 是 wkhtmltopdf 的Python封裝包。首先安裝好下面的依賴包,接著安裝 wkhtmltopdf

pip install requests
pip install beautifulsoup
pip install pdfkit
安裝 wkhtmltopdf

Windows平臺直接在 wkhtmltopdf 官網[2]下載穩定版的進行安裝,安裝完成之後把該程式的執行路徑加入到系統環境 $PATH 變數中,否則 pdfkit 找不到 wkhtmltopdf 就出現錯誤 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令列進行安裝

$ sudo apt-get install wkhtmltopdf  # ubuntu
$ sudo yum intsall wkhtmltopdf # centos

爬蟲實現

一切準備就緒後就可以上程式碼了,不過寫程式碼之前還是先整理一下思緒。程式的目的是要把所有 URL 對應的 html 正文部分儲存到本地,然後利用 pdfkit 把這些檔案轉換成一個 pdf 檔案。我們把任務拆分一下,首先是把某一個 URL 對應的 html 正文儲存到本地,然後找到所有的 URL 執行相同的操作。

用 Chrome 瀏覽器找到頁面正文部分的標籤,按 F12 找到正文對應的 div 標籤: <div class="x-wiki-content">,該 div 是網頁的正文內容。用 requests 把整個頁面載入到本地後,就可以使用 beautifulsoup 操作 HTML 的 dom 元素 來提取正文內容了。

這裡寫圖片描述

具體的實現程式碼如下:用 soup.find_all 函式找到正文標籤,然後把正文部分的內容儲存到 a.html 檔案中。

def parse_url_to_html(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html5lib")
    body = soup.find_all(class_="x-wiki-content")[0]
    html = str(body)
    with open("a.html", 'wb') as f:
        f.write(html)

第二步就是把頁面左側所有 URL 解析出來。採用同樣的方式,找到 左側選單標籤 <ul class="uk-nav uk-nav-side">
這裡寫圖片描述
具體程式碼實現邏輯:因為頁面上有多個uk-nav uk-nav-side的 class 屬性,而真正的目錄列表是第二個。所有的 url 獲取了,url 轉 html 的函式在第一步也寫好了。

def get_url_list():
    """
    獲取所有URL目錄列表
    """
    response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000")
    soup = BeautifulSoup(response.content, "html5lib")
    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

最後一步就是把 html 轉換成pdf檔案了。轉換成 pdf 檔案非常簡單,因為 pdfkit 把所有的邏輯都封裝好了,你只需要呼叫函式 pdfkit.from_file

def save_pdf(htmls):
    """
    把所有html檔案轉換成pdf檔案
    """
    options = {
        'page-size': 'Letter',
        'encoding': "UTF-8",
        'custom-header': [
            ('Accept-Encoding', 'gzip')
        ]
    }
    pdfkit.from_file(htmls, file_name, options=options)

執行 save_pdf 函式,電子書 pdf 檔案就生成了。

總結

總共程式碼量加起來不到50行,不過,且慢,其實上面給出的程式碼省略了一些細節,比如,如何獲取文章的標題,正文內容的 img 標籤使用的是相對路徑,如果要想在 pdf 中正常顯示圖片就需要將相對路徑改為絕對路徑

# body中的img標籤的src相對路徑的改成絕對路徑
        pattern = "(<img .*?src=\")(.*?)(\")"

        def func(m):
            if not m.group(3).startswith("http"):
                rtn = m.group(1) + "http://www.liaoxuefeng.com" + m.group(2) + m.group(3)
                return rtn
            else:
                return m.group(1)+m.group(2)+m.group(3)
        html = re.compile(pattern).sub(func, html)

,還有儲存下來的 html 臨時檔案都要刪除,

htmls = [parse_url_to_html(url, str(index) + ".html") for index, url in enumerate(urls)]
    save_pdf(htmls, file_name)

    for html in htmls:
        os.remove(html)

這些細節末葉都放在github上。
https://gitee.com/liuzhijun1/crawler_html2pdf/blob/master/pdf/crawler.py

【轉自】
http://mp.weixin.qq.com/s/LH8nEFfVH4_tvYWo46CF5Q?utm_source=tool.lu