찾다
백엔드 개발파이썬 튜토리얼Python은 HTML 웹 페이지를 캡처하여 PDF 파일로 저장하는 방법을 구현합니다.

이 글에서는 HTML 웹페이지를 캡처하여 PDF 파일 형태로 저장하는 Python의 방법을 주로 소개합니다. 이를 기반으로 HTML 페이지를 캡처하고 PDF 파일을 생성하는 PyPDF2 모듈의 설치와 관련 Python의 작동 기술을 분석합니다. 예제 형식의 PyPDF2 모듈은 이 문서를 참조할 수 있습니다.

이 문서의 예제에서는 Python이 HTML 웹 페이지를 캡처하고 PDF 파일로 저장하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

1. 소개

오늘은 HTML 웹 페이지를 캡처하고 PDF로 저장하는 방법을 소개하겠습니다. 더 이상 고민할 필요 없이 바로 튜토리얼로 이동하세요. .

2. 준비

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는 네트워크 요청에 사용되고 beautifulsoup는 html 데이터를 작동하는 데 사용됩니다. 이 두 개의 셔틀을 이용하면 작업을 빠르게 끝낼 수 있습니다. scrapy와 같은 크롤러 프레임워크는 필요하지 않습니다. 이렇게 작은 프로그램에 사용하는 것은 약간 과잉입니다. 또한 html 파일을 pdf로 변환하려면 해당 라이브러리 지원도 있어야 합니다. wkhtmltopdf는 html을 여러 플랫폼에 적합한 pdf로 변환할 수 있는 매우 유용한 도구입니다. 먼저 다음 종속성 패키지를 설치하세요

pip install requests
pip install beautifulsoup4
pip install pdfkit

3. wkhtmltopdf

설치 설치가 완료된 후 http://wkhtmltopdf.org/downloads.html에서 wkhtmltopdf의 안정 버전을 직접 다운로드하세요. , 프로그램의 실행 경로가 시스템 환경 $PATH 변수에 추가됩니다. 그렇지 않으면 pdfkit이 wkhtmltopdf를 찾을 수 없으며 "wkhtmltopdf 실행 파일을 찾을 수 없습니다"라는 오류가 나타납니다. Ubuntu 및 CentOS는 명령줄을 사용하여 직접 설치할 수 있습니다

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

3. 데이터 준비

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. 템플릿이 있는 각 기사의 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은 페이지의 링크를 잡기 위해 간단한 크롤러 공유를 구현합니다

파이썬 Baidu 검색결과 페이지의 웹사이트 제목 정보를 가져오는 기능을 구현합니다

위 내용은 Python은 HTML 웹 페이지를 캡처하여 PDF 파일로 저장하는 방법을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?Apr 25, 2025 am 12:28 AM

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?Apr 25, 2025 am 12:24 AM

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 ​​있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?Apr 25, 2025 am 12:21 AM

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?Apr 25, 2025 am 12:13 AM

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?Apr 25, 2025 am 12:11 AM

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Apr 24, 2025 pm 03:53 PM

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Apr 24, 2025 pm 03:49 PM

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기