侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   201

本文实例讲述了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 PdfFileMergermerger = 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 documentoutput = 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 requestspip install beautifulsoup4pip 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-8import osimport reimport timeimport loggingimport pdfkitimport requestsfrom bs4 import BeautifulSoupfrom PyPDF2 import PdfFileMergerhtml_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 urlsdef 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读写/追加excel文件Demo分享
    下一条:
    Python读写docx文件的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客