Python实现抓取HTML网页并以PDF文件形式保存的方法


Posted in Python onMay 08, 2018

本文实例讲述了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

使用示例:

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

def get_url_list():
  """
  获取所有URL目录列表
  :return:
  """
  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

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

html模板:

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

进行保存:

def parse_url_to_html(url, name):
  """
  解析URL,返回HTML内容
  :param url:解析的url
  :param name: 保存的html文件名
  :return: html
  """
  try:
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    # 正文
    body = soup.find_all(class_="x-wiki-content")[0]
    # 标题
    title = soup.find('h4').get_text()
    # 标题加入到正文的最前面,居中显示
    center_tag = soup.new_tag("center")
    title_tag = soup.new_tag('h1')
    title_tag.string = title
    center_tag.insert(1, title_tag)
    body.insert(1, center_tag)
    html = str(body)
    # 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 = html_template.format(content=html)
    html = html.encode("utf-8")
    with open(name, 'wb') as f:
      f.write(html)
    return name
  except Exception as e:
    logging.error("解析错误", exc_info=True)

3. 把html转换成pdf

def save_pdf(htmls, file_name):
  """
  把所有html文件保存到pdf文件
  :param htmls: html文件列表
  :param file_name: pdf文件名
  :return:
  """
  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,
  }
  pdfkit.from_file(htmls, file_name, options=options)

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

merger = PdfFileMerger()
for pdf in pdfs:
  merger.append(open(pdf,'rb'))
  print u"合并完成第"+str(i)+'个pdf'+pdf

完整源码:

# coding=utf-8
import os
import re
import time
import logging
import pdfkit
import requests
from bs4 import BeautifulSoup
from PyPDF2 import PdfFileMerger
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
{content}
</body>
</html>
"""
def parse_url_to_html(url, name):
  """
  解析URL,返回HTML内容
  :param url:解析的url
  :param name: 保存的html文件名
  :return: html
  """
  try:
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    # 正文
    body = soup.find_all(class_="x-wiki-content")[0]
    # 标题
    title = soup.find('h4').get_text()
    # 标题加入到正文的最前面,居中显示
    center_tag = soup.new_tag("center")
    title_tag = soup.new_tag('h1')
    title_tag.string = title
    center_tag.insert(1, title_tag)
    body.insert(1, center_tag)
    html = str(body)
    # 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 = html_template.format(content=html)
    html = html.encode("utf-8")
    with open(name, 'wb') as f:
      f.write(html)
    return name
  except Exception as e:
    logging.error("解析错误", exc_info=True)
def get_url_list():
  """
  获取所有URL目录列表
  :return:
  """
  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
def save_pdf(htmls, file_name):
  """
  把所有html文件保存到pdf文件
  :param htmls: html文件列表
  :param file_name: pdf文件名
  :return:
  """
  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,
  }
  pdfkit.from_file(htmls, file_name, options=options)
def main():
  start = time.time()
  file_name = u"liaoxuefeng_Python3_tutorial"
  urls = get_url_list()
  for index, url in enumerate(urls):
   parse_url_to_html(url, str(index) + ".html")
  htmls =[]
  pdfs =[]
  for i in range(0,124):
    htmls.append(str(i)+'.html')
    pdfs.append(file_name+str(i)+'.pdf')
    save_pdf(str(i)+'.html', file_name+str(i)+'.pdf')
    print u"转换完成第"+str(i)+'个html'
  merger = PdfFileMerger()
  for pdf in pdfs:
    merger.append(open(pdf,'rb'))
    print u"合并完成第"+str(i)+'个pdf'+pdf
  output = open(u"廖雪峰Python_all.pdf", "wb")
  merger.write(output)
  print u"输出PDF成功!"
  for html in htmls:
    os.remove(html)
    print u"删除临时文件"+html
  for pdf in pdfs:
    os.remove(pdf)
    print u"删除临时文件"+pdf
  total_time = time.time() - start
  print(u"总共耗时:%f 秒" % total_time)
if __name__ == '__main__':
  main()

更多Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python Mysql数据库操作 Perl操作Mysql数据库
Jan 12 Python
Python中给List添加元素的4种方法分享
Nov 28 Python
python绘制条形图方法代码详解
Dec 19 Python
Python解决八皇后问题示例
Apr 22 Python
Python定时任务sched模块用法示例
Jul 16 Python
浅谈Python的list中的选取范围
Nov 12 Python
Python pip替换为阿里源的方法步骤
Jul 02 Python
python机器学习包mlxtend的安装和配置详解
Aug 21 Python
Python Request类源码实现方法及原理解析
Aug 17 Python
Python安装第三方库攻略(pip和Anaconda)
Oct 15 Python
python基于exchange函数发送邮件过程详解
Nov 06 Python
Python更改pip镜像源的方法示例
Dec 01 Python
Python读写docx文件的方法
May 08 #Python
python docx 中文字体设置的操作方法
May 08 #Python
Python解析并读取PDF文件内容的方法
May 08 #Python
python-docx修改已存在的Word文档的表格的字体格式方法
May 08 #Python
对Python中gensim库word2vec的使用详解
May 08 #Python
用python处理MS Word的实例讲解
May 08 #Python
基于python批量处理dat文件及科学计算方法详解
May 08 #Python
You might like
PHP下获取上个月、下个月、本月的日期(strtotime,date)
2014/02/02 PHP
php 伪静态之IIS篇
2014/06/02 PHP
PHP错误Allowed memory size of 67108864 bytes exhausted的3种解决办法
2014/07/28 PHP
php的crc32函数使用时需要注意的问题(不然就是坑)
2015/04/21 PHP
php图片添加水印例子
2016/07/20 PHP
magento后台无法登录解决办法的两种方法
2016/12/09 PHP
老生常谈文本文件和二进制文件的区别
2017/02/27 PHP
Jquery Select操作方法集合脚本之家特别版
2010/05/17 Javascript
JavaScript中函数声明优先于变量声明的实例分析
2012/03/01 Javascript
js获取当前日期代码适用于网页头部
2013/06/27 Javascript
将查询条件的input、select清空
2014/01/14 Javascript
jQuery中:enabled选择器用法实例
2015/01/04 Javascript
程序员必知35个jQuery 代码片段
2015/11/05 Javascript
js根据手机客户端浏览器类型,判断跳转官网/手机网站多个实例代码
2016/04/30 Javascript
JS图片压缩(pc端和移动端都适用)
2017/01/12 Javascript
js+html5实现半透明遮罩层弹框效果
2020/08/24 Javascript
vue-cli 目录结构详细讲解总结
2019/01/15 Javascript
基于Vue sessionStorage实现保留搜索框搜索内容
2020/06/01 Javascript
[56:35]DOTA2上海特级锦标赛C组小组赛#1 OG VS Archon第二局
2016/02/27 DOTA
[49:07]VGJ.T vs Optic Supermajor小组赛D组 BO3 第二场 6.3
2018/06/04 DOTA
[48:00]完美世界DOTA2联赛循环赛 Forest vs Inki BO2第二场 11.04
2020/11/04 DOTA
[54:05]DOTA2-DPC中国联赛定级赛 SAG vs iG BO3第一场 1月9日
2021/03/11 DOTA
Python+django实现文件上传
2016/01/17 Python
python开发环境PyScripter中文乱码问题解决方案
2016/09/11 Python
python+opencv实现的简单人脸识别代码示例
2017/11/14 Python
Python中如何引入第三方模块
2020/05/27 Python
用Python实现定时备份Mongodb数据并上传到FTP服务器
2021/01/27 Python
英国设计的甲板鞋和船鞋:Chatham
2018/12/06 全球购物
顶岗实习接收函
2014/01/09 职场文书
结婚典礼证婚词
2014/01/11 职场文书
借款担保书范文
2014/05/13 职场文书
高三英语教学计划
2015/01/23 职场文书
电力安全教育培训心得体会
2016/01/11 职场文书
八年级作文之友谊
2019/12/02 职场文书
详解Go语言运用广度优先搜索走迷宫
2021/06/23 Python
python中的3种定义类方法
2021/11/27 Python