我想使用 PyQt5 截取网页的屏幕截图。 (一个完整的网页,包括用户除非向下滚动才能看到的内容。)

Supposedly, it is possible to do this in PyQt5 using QtWebEngine 。你会怎么做呢?我特别不希望用户看到浏览器窗口打开或呈现。我只想要一个 PNG 文件中的屏幕截图。

最佳答案

以下是 QtWebEngine(版本 5.12)的示例:

import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt, QUrl, QTimer
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings


class Screenshot(QWebEngineView):

    def capture(self, url, output_file):
        self.output_file = output_file
        self.load(QUrl(url))
        self.loadFinished.connect(self.on_loaded)
        # Create hidden view without scrollbars
        self.setAttribute(Qt.WA_DontShowOnScreen)
        self.page().settings().setAttribute(
            QWebEngineSettings.ShowScrollBars, False)
        self.show()

    def on_loaded(self):
        size = self.page().contentsSize().toSize()
        self.resize(size)
        # Wait for resize
        QTimer.singleShot(1000, self.take_screenshot)

    def take_screenshot(self):
        self.grab().save(self.output_file, b'PNG')
        self.app.quit()


app = QApplication(sys.argv)
s = Screenshot()
s.app = app
s.capture('https://pypi.org/project/PyQt5/', 'webpage.png')
sys.exit(app.exec_())

关于python - 在 PyQt5 中截取网页的屏幕截图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55231170/

10-12 19:54