在Python中将多个网页保存为PDF文件

问题描述 投票:0回答:1

我需要在Python中将多个网页保存为PDF文件。我在这个方向找到了几个例子,一些使用 PyQt5,一些使用 wkhtmltopdf。

即使我在 Windows 中设置了环境变量,我也无法成功使用 wkhtmltopdf。

另一方面,我可以使用 PyQt5 将网页另存为 PDF 文件。

我尝试修改该示例以循环运行它,但它不起作用。它只保存一些文件,但不是全部
我需要您就 PyQt5 或 wkhtmltopdf 或其他方式的问题提供帮助。这是我的代码。

import requests
from bs4 import BeautifulSoup
import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication
from pathlib import Path

app = QtWidgets.QApplication(sys.argv)


def save_webpage_as_pdf(url, output_file):
    loader = QtWebEngineWidgets.QWebEngineView()
    loader.setZoomFactor(1)
    layout = QPageLayout()
    layout.setPageSize(QPageSize(QPageSize.A4Extra))
    layout.setOrientation(QPageLayout.Portrait)
    loader.load(QUrl(url))
    loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())

    def emit_pdf(finished):
        loader.page().printToPdf(output_file, pageLayout=layout)

    loader.loadFinished.connect(emit_pdf)


catalogue_url = "https://debis.deu.edu.tr/ders-katalog/2023-2024/tr/"
department_url = "bolum_1129_tr.html"
reqs = requests.get(catalogue_url + department_url)
content = reqs.content.decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')

urls = soup.find_all('a')
start_index = [url.get('href') for url in urls].index("../havuz/1129tr.pdf")
end_index = [url.get('href') for url in urls].index("bolum_1129_tr.html")
for i in range(start_index + 1, end_index):
    course_url = catalogue_url + urls[i].get('href')
    print(course_url)
    if Path("File(" + str(i) + ").pdf").is_file() == False:
        save_webpage_as_pdf(course_url, "File(" + str(i) + ").pdf")

sys.exit(app.exec_())
python pyqt5 wkhtmltopdf printing-web-page
1个回答
1
投票

问题是您在打印完成后立即退出应用程序。这不会立即发生,因为 IO 访问和事件循环之间的交互让某些操作持续一段时间,但最终会尽快退出。

一种可能的解决方案是从函数返回页面,然后仅连接第 last 的信号。您还应该仅在至少打印一页时启动应用程序循环。


def save_webpage_as_pdf(url, output_file):
    ...
    return loader.page()

...
lastPage = None
for i in range(start_index + 1, end_index):
    course_url = catalogue_url + urls[i].get('href')
    path = f"File({i}).pdf"
    if not Path(path).is_file():
        lastPage = save_webpage_as_pdf(course_url, path)

if lastPage is not None:
    lastPage.pdfPrintingFinished.connect(app.quit)
    sys.exit(app.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.