首頁 後端開發 Python教學 Python實作抓取HTML網頁並以PDF檔案形式保存的方法

Python實作抓取HTML網頁並以PDF檔案形式保存的方法

May 08, 2018 am 11:55 AM
html python 網頁

這篇文章主要介紹了Python實現抓取HTML網頁並以PDF文件形式保存的方法,結合實例形式分析了PyPDF2模組的安裝及Python抓取HTML頁面並基於PyPDF2模組生成pdf文件的相關操作技巧,需要的朋友可以參考下

本文實例講述了Python實現抓取HTML網頁並以PDF文件形式保存的方法。分享給大家參考,具體如下:

一、前言

今天介紹將HTML網頁抓取下來,然後以PDF儲存,廢話不多說直接進入教學。

二、準備工作

1. PyPDF2的安裝使用(用來合併PDF):

PyPDF2版本: 1.25.1

安裝:

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, &#39;html.parser&#39;)
    # 正文
    body = soup.find_all(class_="x-wiki-content")[0]
    # 标题
    title = soup.find(&#39;h4&#39;).get_text()
    # 标题加入到正文的最前面,居中显示
    center_tag = soup.new_tag("center")
    title_tag = soup.new_tag(&#39;h1&#39;)
    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, &#39;wb&#39;) 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 = {
    &#39;page-size&#39;: &#39;Letter&#39;,
    &#39;margin-top&#39;: &#39;0.75in&#39;,
    &#39;margin-right&#39;: &#39;0.75in&#39;,
    &#39;margin-bottom&#39;: &#39;0.75in&#39;,
    &#39;margin-left&#39;: &#39;0.75in&#39;,
    &#39;encoding&#39;: "UTF-8",
    &#39;custom-header&#39;: [
      (&#39;Accept-Encoding&#39;, &#39;gzip&#39;)
    ],
    &#39;cookie&#39;: [
      (&#39;cookie-name1&#39;, &#39;cookie-value1&#39;),
      (&#39;cookie-name2&#39;, &#39;cookie-value2&#39;),
    ],
    &#39;outline-depth&#39;: 10,
  }
  pdfkit.from_file(htmls, file_name, options=options)
登入後複製

#4. 把轉換好的單一PDF合併為一個PDF

merger = PdfFileMerger()
for pdf in pdfs:
  merger.append(open(pdf,&#39;rb&#39;))
  print u"合并完成第"+str(i)+&#39;个pdf&#39;+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, &#39;html.parser&#39;)
    # 正文
    body = soup.find_all(class_="x-wiki-content")[0]
    # 标题
    title = soup.find(&#39;h4&#39;).get_text()
    # 标题加入到正文的最前面,居中显示
    center_tag = soup.new_tag("center")
    title_tag = soup.new_tag(&#39;h1&#39;)
    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, &#39;wb&#39;) 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(&#39;href&#39;)
    urls.append(url)
  return urls
def save_pdf(htmls, file_name):
  """
  把所有html文件保存到pdf文件
  :param htmls: html文件列表
  :param file_name: pdf文件名
  :return:
  """
  options = {
    &#39;page-size&#39;: &#39;Letter&#39;,
    &#39;margin-top&#39;: &#39;0.75in&#39;,
    &#39;margin-right&#39;: &#39;0.75in&#39;,
    &#39;margin-bottom&#39;: &#39;0.75in&#39;,
    &#39;margin-left&#39;: &#39;0.75in&#39;,
    &#39;encoding&#39;: "UTF-8",
    &#39;custom-header&#39;: [
      (&#39;Accept-Encoding&#39;, &#39;gzip&#39;)
    ],
    &#39;cookie&#39;: [
      (&#39;cookie-name1&#39;, &#39;cookie-value1&#39;),
      (&#39;cookie-name2&#39;, &#39;cookie-value2&#39;),
    ],
    &#39;outline-depth&#39;: 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實作抓取HTML網頁並以PDF檔案形式保存的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1666
14
CakePHP 教程
1425
52
Laravel 教程
1325
25
PHP教程
1273
29
C# 教程
1252
24
PHP和Python:解釋了不同的範例 PHP和Python:解釋了不同的範例 Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

HTML:結構,CSS:樣式,JavaScript:行為 HTML:結構,CSS:樣式,JavaScript:行為 Apr 18, 2025 am 12:09 AM

HTML、CSS和JavaScript在Web開發中的作用分別是:1.HTML定義網頁結構,2.CSS控製網頁樣式,3.JavaScript添加動態行為。它們共同構建了現代網站的框架、美觀和交互性。

在PHP和Python之間進行選擇:指南 在PHP和Python之間進行選擇:指南 Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

sublime怎麼運行代碼python sublime怎麼運行代碼python Apr 16, 2025 am 08:48 AM

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

PHP和Python:深入了解他們的歷史 PHP和Python:深入了解他們的歷史 Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

HTML的未來:網絡設計的發展和趨勢 HTML的未來:網絡設計的發展和趨勢 Apr 17, 2025 am 12:12 AM

HTML的未來充滿了無限可能。 1)新功能和標準將包括更多的語義化標籤和WebComponents的普及。 2)網頁設計趨勢將繼續向響應式和無障礙設計發展。 3)性能優化將通過響應式圖片加載和延遲加載技術提升用戶體驗。

Golang vs. Python:性能和可伸縮性 Golang vs. Python:性能和可伸縮性 Apr 19, 2025 am 12:18 AM

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

See all articles