Python抓取HTML网页并以PDF保存

目录(?)[+]

一、前言

今天介绍将HTML网页抓取下来,然后以PDF保存,废话不多说直接进入教程。

今天的例子以廖雪峰老师的Python教程网站为例:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

二、准备工作

  1. PyPDF2的安装使用(用来合并PDF):

    PyPDF2版本:1.25.1

    https://pypi.python.org/pypi/PyPDF2/1.25.1

    https://github.com/mstamy2/PyPDF2

    安装:

    pip install PyPDF2

    使用示例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    from PyPDF2  import PdfFileMerger
    merger  = PdfFileMerger ( )
    input1  =  open ( "hql_1_20.pdf" ,  "rb" )
    input2  =  open ( "hql_21_40.pdf" ,  "rb" )
    merger. append (input1 )
    merger. append (input2 )
    # Write to an output PDF document
    output  =  open ( "hql_all.pdf" ,  "wb" )
    merger. write (output )
  2. requests、beautifulsoup 是爬虫两大神器,reuqests 用于网络请求,beautifusoup 用于操作 html 数据。有了这两把梭子,干起活来利索。scrapy 这样的爬虫框架我们就不用了,这样的小程序派上它有点杀鸡用牛刀的意思。此外,既然是把 html 文件转为 pdf,那么也要有相应的库支持, wkhtmltopdf 就是一个非常的工具,它可以用适用于多平台的 html 到 pdf 的转换,pdfkit 是 wkhtmltopdf 的Python封装包。首先安装好下面的依赖包
    pip install requests
    pip install beautifulsoup4
    pip install pdfkit

  3. 安装 wkhtmltopdf

    Windows平台直接在 http://wkhtmltopdf.org/downloads.html 下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程序的执行路径加入到系统环境 $PATH 变量中,否则 pdfkit 找不到 wkhtmltopdf 就出现错误 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行进行安装

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

     

三、数据准备

1.获取每篇文章的url

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. def get_url_list():  
  2.     """ 
  3.     获取所有URL目录列表 
  4.     :return: 
  5.     """  
  6.     response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000")  
  7.     soup = BeautifulSoup(response.content, "html.parser")  
  8.     menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1]  
  9.     urls = []  
  10.     for li in menu_tag.find_all("li"):  
  11.         url = "http://www.liaoxuefeng.com" + li.a.get('href')  
  12.         urls.append(url)  
  13.     return urls  


2.通过文章url用模板保存每篇文章的HTML文件

html模板:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. html_template = """ 
  2. <!DOCTYPE html> 
  3. <html lang="en"> 
  4. <head> 
  5.     <meta charset="UTF-8"> 
  6. </head> 
  7. <body> 
  8. {content} 
  9. </body> 
  10. </html> 
  11.  
  12. """  


进行保存:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. def parse_url_to_html(url, name):  
  2.     """ 
  3.     解析URL,返回HTML内容 
  4.     :param url:解析的url 
  5.     :param name: 保存的html文件名 
  6.     :return: html 
  7.     """  
  8.     try:  
  9.         response = requests.get(url)  
  10.         soup = BeautifulSoup(response.content, 'html.parser')  
  11.         # 正文  
  12.         body = soup.find_all(class_="x-wiki-content")[0]  
  13.         # 标题  
  14.         title = soup.find('h4').get_text()  
  15.   
  16.         # 标题加入到正文的最前面,居中显示  
  17.         center_tag = soup.new_tag("center")  
  18.         title_tag = soup.new_tag('h1')  
  19.         title_tag.string = title  
  20.         center_tag.insert(1, title_tag)  
  21.         body.insert(1, center_tag)  
  22.         html = str(body)  
  23.         # body中的img标签的src相对路径的改成绝对路径  
  24.         pattern = "(<img .*?src=\")(.*?)(\")"  
  25.   
  26.         def func(m):  
  27.             if not m.group(3).startswith("http"):  
  28.                 rtn = m.group(1) + "http://www.liaoxuefeng.com" + m.group(2) + m.group(3)  
  29.                 return rtn  
  30.             else:  
  31.                 return m.group(1)+m.group(2)+m.group(3)  
  32.         html = re.compile(pattern).sub(func, html)  
  33.         html = html_template.format(content=html)  
  34.         html = html.encode("utf-8")  
  35.         with open(name, 'wb') as f:  
  36.             f.write(html)  
  37.         return name  
  38.   
  39.     except Exception as e:  
  40.   
  41.         logging.error("解析错误", exc_info=True)  


3.把html转换成pdf

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. def save_pdf(htmls, file_name):  
  2.     """ 
  3.     把所有html文件保存到pdf文件 
  4.     :param htmls:  html文件列表 
  5.     :param file_name: pdf文件名 
  6.     :return: 
  7.     """  
  8.     options = {  
  9.         'page-size''Letter',  
  10.         'margin-top''0.75in',  
  11.         'margin-right''0.75in',  
  12.         'margin-bottom''0.75in',  
  13.         'margin-left''0.75in',  
  14.         'encoding'"UTF-8",  
  15.         'custom-header': [  
  16.             ('Accept-Encoding''gzip')  
  17.         ],  
  18.         'cookie': [  
  19.             ('cookie-name1''cookie-value1'),  
  20.             ('cookie-name2''cookie-value2'),  
  21.         ],  
  22.         'outline-depth'10,  
  23.     }  
  24.     pdfkit.from_file(htmls, file_name, options=options)  


4.把转换好的单个PDF合并为一个PDF

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. merger = PdfFileMerger()  
  2. for pdf in pdfs:  
  3.    merger.append(open(pdf,'rb'))  
  4.    print u"合并完成第"+str(i)+'个pdf'+pdf  



完整源码:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2. import os  
  3. import re  
  4. import time  
  5. import logging  
  6. import pdfkit  
  7. import requests  
  8. from bs4 import BeautifulSoup  
  9. from PyPDF2 import PdfFileMerger  
  10.   
  11. html_template = """ 
  12. <!DOCTYPE html> 
  13. <html lang="en"> 
  14. <head> 
  15.     <meta charset="UTF-8"> 
  16. </head> 
  17. <body> 
  18. {content} 
  19. </body> 
  20. </html> 
  21.  
  22. """  
  23.   
  24.   
  25. def parse_url_to_html(url, name):  
  26.     """ 
  27.     解析URL,返回HTML内容 
  28.     :param url:解析的url 
  29.     :param name: 保存的html文件名 
  30.     :return: html 
  31.     """  
  32.     try:  
  33.         response = requests.get(url)  
  34.         soup = BeautifulSoup(response.content, 'html.parser')  
  35.         # 正文  
  36.         body = soup.find_all(class_="x-wiki-content")[0]  
  37.         # 标题  
  38.         title = soup.find('h4').get_text()  
  39.   
  40.         # 标题加入到正文的最前面,居中显示  
  41.         center_tag = soup.new_tag("center")  
  42.         title_tag = soup.new_tag('h1')  
  43.         title_tag.string = title  
  44.         center_tag.insert(1, title_tag)  
  45.         body.insert(1, center_tag)  
  46.         html = str(body)  
  47.         # body中的img标签的src相对路径的改成绝对路径  
  48.         pattern = "(<img .*?src=\")(.*?)(\")"  
  49.   
  50.         def func(m):  
  51.             if not m.group(3).startswith("http"):  
  52.                 rtn = m.group(1) + "http://www.liaoxuefeng.com" + m.group(2) + m.group(3)  
  53.                 return rtn  
  54.             else:  
  55.                 return m.group(1)+m.group(2)+m.group(3)  
  56.         html = re.compile(pattern).sub(func, html)  
  57.         html = html_template.format(content=html)  
  58.         html = html.encode("utf-8")  
  59.         with open(name, 'wb') as f:  
  60.             f.write(html)  
  61.         return name  
  62.   
  63.     except Exception as e:  
  64.   
  65.         logging.error("解析错误", exc_info=True)  
  66.   
  67.   
  68. def get_url_list():  
  69.     """ 
  70.     获取所有URL目录列表 
  71.     :return: 
  72.     """  
  73.     response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000")  
  74.     soup = BeautifulSoup(response.content, "html.parser")  
  75.     menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1]  
  76.     urls = []  
  77.     for li in menu_tag.find_all("li"):  
  78.         url = "http://www.liaoxuefeng.com" + li.a.get('href')  
  79.         urls.append(url)  
  80.     return urls  
  81.   
  82.   
  83. def save_pdf(htmls, file_name):  
  84.     """ 
  85.     把所有html文件保存到pdf文件 
  86.     :param htmls:  html文件列表 
  87.     :param file_name: pdf文件名 
  88.     :return: 
  89.     """  
  90.     options = {  
  91.         'page-size''Letter',  
  92.         'margin-top''0.75in',  
  93.         'margin-right''0.75in',  
  94.         'margin-bottom''0.75in',  
  95.         'margin-left''0.75in',  
  96.         'encoding'"UTF-8",  
  97.         'custom-header': [  
  98.             ('Accept-Encoding''gzip')  
  99.         ],  
  100.         'cookie': [  
  101.             ('cookie-name1''cookie-value1'),  
  102.             ('cookie-name2''cookie-value2'),  
  103.         ],  
  104.         'outline-depth'10,  
  105.     }  
  106.     pdfkit.from_file(htmls, file_name, options=options)  
  107.   
  108.   
  109. def main():  
  110.     start = time.time()  
  111.     file_name = u"liaoxuefeng_Python3_tutorial"  
  112.     urls = get_url_list()  
  113.     for index, url in enumerate(urls):  
  114.       parse_url_to_html(url, str(index) + ".html")  
  115.     htmls =[]  
  116.     pdfs =[]  
  117.     for i in range(0,124):  
  118.         htmls.append(str(i)+'.html')  
  119.         pdfs.append(file_name+str(i)+'.pdf')  
  120.   
  121.         save_pdf(str(i)+'.html', file_name+str(i)+'.pdf')  
  122.   
  123.         print u"转换完成第"+str(i)+'个html'  
  124.   
  125.     merger = PdfFileMerger()  
  126.     for pdf in pdfs:  
  127.        merger.append(open(pdf,'rb'))  
  128.        print u"合并完成第"+str(i)+'个pdf'+pdf  
  129.   
  130.     output = open(u"廖雪峰Python_all.pdf""wb")  
  131.     merger.write(output)  
  132.   
  133.     print u"输出PDF成功!"  
  134.   
  135.     for html in htmls:  
  136.         os.remove(html)  
  137.         print u"删除临时文件"+html  
  138.   
  139.     for pdf in pdfs:  
  140.         os.remove(pdf)  
  141.         print u"删除临时文件"+pdf  
  142.   
  143.     total_time = time.time() - start  
  144.     print(u"总共耗时:%f 秒" % total_time)  
  145.   
  146.   
  147. if __name__ == '__main__':  
  148.     main()  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值