为了账号安全,请及时绑定邮箱和手机立即绑定

在 PyQt5 中截取网页的截图

在 PyQt5 中截取网页的截图

小唯快跑啊 2021-12-09 10:30:22
我想使用 PyQt5 截取网页的屏幕截图。(一个完整的网页,包括用户除非向下滚动才能看到的内容。)据说,可以使用 QtWebEngine 在 PyQt5 中做到这一点。你会怎么做呢?我特别不希望用户看到浏览器窗口打开或呈现。我只想要一个 PNG 文件的屏幕截图。
查看完整描述

2 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

以下是 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_())


查看完整回答
反对 回复 2021-12-09
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

- 此代码在: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')

结果:

//img1.sycdn.imooc.com//61b16a6f0001694f02901291.jpg

查看完整回答
反对 回复 2021-12-09
  • 2 回答
  • 0 关注
  • 348 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信