Python + Scrapy 抓取網(wǎng)站并生成PDF文檔

有時候看到一些文檔想保存為PDF捧存,但是太多頁屹培,手動保存也太麻煩迂苛。于是考慮尋找Python實現(xiàn)的方法—— pdfkit
更多關(guān)注:
http://www.mknight.cn

wkhtmltopdf

  • wkhtmltopdf主要用于HTML生成PDF禁悠。
  • pdfkit是基于wkhtmltopdf的python封裝,支持URL睛藻,本地文件启上,文本內(nèi)容到PDF的轉(zhuǎn)換,其最終還是調(diào)用wkhtmltopdf命令店印。是目前接觸到的python生成pdf效果較好的冈在。

安裝

yum and pip

yum install wkhtmltopdf
pip install pdfkit

tar.xz

如果yum找不到,可以手動下載

wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
cd wkhtmltox/bin
cp ./* /usr/sbin/

驗證

[root@xxx tmp]# wkhtmltopdf -V
wkhtmltopdf 0.12.4 (with patched qt)

相關(guān)詳細(xì)介紹參考pdfkit + wkhtmltopdf

Scrapy

新建項目

scrapy starproject fox

目錄結(jié)構(gòu):

.
├── scrapy.cfg
└── fox
    ├── __init__.py
    ├── items.py
    ├── middlewares.py
    ├── pipelines.py
    ├── settings.py
    └── spiders
        ├── __init__.py

流程

要抓取的網(wǎng)站
[圖片上傳失敗...(image-2e3267-1512379852014)]
提取URL-》提取內(nèi)容-》保存HTML-》生成PDF

編輯爬蟲文件

spiders/read.py

import scrapy, os
from scrapy.selector import Selector
from scrapy.http import Request
from fox import items as ReadItem

base_url = 'http://python3-cookbook.readthedocs.io/zh_CN/latest/'


class ReadSpider(scrapy.spiders.Spider):
    name = "read"
    start_urls = [
        'http://python3-cookbook.readthedocs.io/zh_CN/latest/',
    ]

    def parse(self, response):
        links = []
        s = Selector(response)
        items = s.xpath('//li[@class="toctree-l2"]/a')
        #循環(huán)出所有的章節(jié)URL
        for i in range(len(items)):
            url = s.xpath('//li[@class="toctree-l2"]/a/@href').extract()[i]
            #取出href
            if 'c0' in url or 'c1' in url:
                #排除其他無關(guān)URL
                c_url = base_url + url
                #拼接
                links.append(c_url)
            else:
                print('no', url)
        for link in links:
            print(link)
            yield Request(link, callback=self.get_content)

    def get_content(self, response):
        #根據(jù)URL,獲取內(nèi)容
        print('#########################獲取HTML#########################')
        item = ReadItem.ReadItem()
        content = response.xpath('//div[@class="section"]').extract()[0]
        item['content'] = content
        item['url'] = response.url
        yield item

items.py

import scrapy
class ReadItem(scrapy.Item):
    content = scrapy.Field()
    url = scrapy.Field()

piplines.py

import os
html_template = """
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
        {content}
        </body>
        </html>
        """


class ReadPipeline(object):
    def process_item(self, item, spider):
        print('#########################獲取Content#########################')
        url = item['url']
        content = item['content']
        html = html_template.format(content=content)
        file_name = url.split('/')[5][1:] + url.split('/')[6][1:3] + '.html'
        #拼接要保存的HTML文件名
        file_name = os.path.join(os.path.abspath('.'), 'htmls', file_name)
        print(file_name)
        #將拼接好的html寫入文件
        with open(file_name, 'a+', encoding='utf-8') as f:
            f.write(html)

settings.py

ITEM_PIPELINES = {
    'fox.pipelines.ReadPipeline': 300,
#啟用該piplines
}

HTML ——》 PDF

import os
import pdfkit

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'),
    ],
    'outline-depth': 10,
}

filedir = os.path.join(os.path.abspath('.'), 'htmls')
files = os.listdir(filedir)
desc_file = os.path.join(os.path.abspath('.'), 'all.html')
#
for i in files:
    # 遍歷單個文件按摘,讀取行數(shù)
    print(i)
    cc = os.path.join(os.path.abspath('.'), 'htmls', i)
    with open(cc, 'r', encoding='utf-8') as f:
        with open(desc_file, 'a+', encoding='utf-8') as new:
            new.write(f.read())

pdf = pdfkit.from_file('all.html', 'out.pdf', options=options)

驗證

image

就這樣生成了PDF文件包券,如果確認(rèn)HTML文件帶<h1>、<h2>標(biāo)簽但是沒有生成目錄炫贤,那就說明是python版本問題溅固,親身經(jīng)歷的坑!Python 3.6@颊洹J坦!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末俩垃,一起剝皮案震驚了整個濱河市励幼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌口柳,老刑警劉巖苹粟,帶你破解...
    沈念sama閱讀 216,744評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異跃闹,居然都是意外死亡嵌削,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評論 3 392
  • 文/潘曉璐 我一進(jìn)店門望艺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來苛秕,“玉大人,你說我怎么就攤上這事找默⊥Ы伲” “怎么了?”我有些...
    開封第一講書人閱讀 163,105評論 0 353
  • 文/不壞的土叔 我叫張陵惩激,是天一觀的道長店煞。 經(jīng)常有香客問我,道長风钻,這世上最難降的妖魔是什么顷蟀? 我笑而不...
    開封第一講書人閱讀 58,242評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮骡技,結(jié)果婚禮上鸣个,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好囤萤,可當(dāng)我...
    茶點故事閱讀 67,269評論 6 389
  • 文/花漫 我一把揭開白布昼窗。 她就那樣靜靜地躺著,像睡著了一般阁将。 火紅的嫁衣襯著肌膚如雪膏秫。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,215評論 1 299
  • 那天做盅,我揣著相機與錄音缤削,去河邊找鬼。 笑死吹榴,一個胖子當(dāng)著我的面吹牛亭敢,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播图筹,決...
    沈念sama閱讀 40,096評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼帅刀,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了远剩?” 一聲冷哼從身側(cè)響起扣溺,我...
    開封第一講書人閱讀 38,939評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎瓜晤,沒想到半個月后锥余,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,354評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡痢掠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,573評論 2 333
  • 正文 我和宋清朗相戀三年驱犹,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片足画。...
    茶點故事閱讀 39,745評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡雄驹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出淹辞,到底是詐尸還是另有隱情医舆,我是刑警寧澤,帶...
    沈念sama閱讀 35,448評論 5 344
  • 正文 年R本政府宣布象缀,位于F島的核電站彬向,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏攻冷。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,048評論 3 327
  • 文/蒙蒙 一遍希、第九天 我趴在偏房一處隱蔽的房頂上張望等曼。 院中可真熱鬧,春花似錦、人聲如沸禁谦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽州泊。三九已至丧蘸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間遥皂,已是汗流浹背力喷。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留演训,地道東北人弟孟。 一個月前我還...
    沈念sama閱讀 47,776評論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像样悟,于是被迫代替她去往敵國和親拂募。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,652評論 2 354

推薦閱讀更多精彩內(nèi)容