python爬取网页内容转换为PDF文件

yipeiwu_com6年前Python爬虫

本文实例为大家分享了python爬取网页内容转换为PDF的具体代码,供大家参考,具体内容如下

将廖雪峰的学习教程转换成PDF文件,代码只适合该网站,如果需要其他网站的教程,可靠需要进行稍微的修改。

# coding=utf-8 
import os 
import re 
import time 
import pdfkit 
import requests 
from bs4 import BeautifulSoup 
from PyPDF2 import PdfFileMerger
import sys
reload(sys)
sys.setdefaultencoding('utf8')

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:
    print "解析错误!"

#----------------------------------------------------------------------
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)

#----------------------------------------------------------------------
def changeDir(dir_name):
  """
  目录切换
  """
  if not os.path.exists(dir_name):
    os.mkdir(dir_name)

  os.chdir(dir_name)
#----------------------------------------------------------------------
if __name__ == '__main__':
  #存放文件的路径
  dir_name = '/home/Python/Html'  
  changeDir(dir_name)
  main() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

利用selenium爬虫抓取数据的基础教程

写在前面 本来这篇文章该几个月前写的,后来忙着忙着就给忘记了。 ps:事多有时候反倒会耽误事。 几个月前,记得群里一朋友说想用selenium去爬数据,关于爬数据,一般是模拟访问某...

Python selenium抓取微博内容的示例代码

Python selenium抓取微博内容的示例代码

Selenium简介与安装 Selenium是什么? Selenium也是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持...

Python爬虫抓取技术的一些经验

Python爬虫抓取技术的一些经验

前言 web是一个开放的平台,这也奠定了web从90年代初诞生直至今日将近30年来蓬勃的发展。然而,正所谓成也萧何败也萧何,开放的特性、搜索引擎以及简单易学的html、css技术使得we...

深入理解Python爬虫代理池服务

深入理解Python爬虫代理池服务

在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东西不能开源出来。...

python3爬取数据至mysql的方法

本文实例为大家分享了python3爬取数据至mysql的具体代码,供大家参考,具体内容如下 直接贴代码 #!/usr/local/bin/python3.5 # -*- codin...