在PyQt5中截取网页的屏幕截图

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

我想使用PyQt5来截取网页的截图。 (完整的网页,包括用户不会看到的内容,除非他们向下滚动。)

Supposedly, it is possible to do this in PyQt5 using QtWebEngine。你会怎么做?我特别不希望用户看到浏览器窗口打开或渲染。我只想在PNG文件中截图。

python pyqt pyqt5 qtwebengine
1个回答
0
投票

- 此代码已经过测试:QT_VERSION_STR = 5.12.1,PYQT_VERSION_STR = 5.12

注意:QtWebKit在Qt 5.5上游被弃用,在5.6中被删除。

相反,它被替换为“QtWebEngineWidgets”。所以你必须在代码中进行更改。

有关更多信息:http://doc.qt.io/qt-5/qtwebenginewidgets-qtwebkitportingguide.html

from PyQt5.QtGui import QPainter, QImage
from PyQt5 import QtWebKitWidgets
from functools import partial



class Screenshot(QtWebKitWidgets.QWebView):
    def __init__(self):
        QtWebKitWidgets.QWebView.__init__(self)

    def capture(self, url, output_file):
        self.load(QUrl(url))
        self.loadFinished.connect(partial(self.onDone, output_file))

    def onDone(self,output_file):
        # set to webpage size
        frame = self.page().mainFrame()
        self.page().setViewportSize(frame.contentsSize())
        # render image
        image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
        painter = QPainter(image)
        frame.render(painter)
        painter.end()
        image.save(output_file)


s = Screenshot()
s.capture('https://pypi.org/project/PyQt5/', 'C:/Users/user/Desktop/web_page.png')

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.