【问题标题】:Taking a screenshot of a web page in PyQt5在 PyQt5 中截取网页截图
【发布时间】:2019-08-09 09:36:15
【问题描述】:

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

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

【问题讨论】:

  • 我没有测试过。然而,我的兴趣是用 PyQt5 来做这件事。
  • 编辑问题以删除 PyQt4 引用
  • 你见过this?。不确定它是否会截取用户看不到的东西的屏幕截图......

标签: python pyqt pyqt5 qtwebengine


【解决方案1】:

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

【讨论】:

  • 除了等待 1000 毫秒之外,还有更好的等待调整大小的方法吗?如果当时没有调整页面大小,这似乎效率低下并且可能很危险
【解决方案2】:

-此代码已在 QT_VERSION_STR = 5.12.1PYQT_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')

结果:

【讨论】:

  • 这看起来像我想要的,但是在粘贴到 SO 时丢失了一些代码。没有类定义等。运行时,此代码是否显示浏览器窗口?我想让它对用户隐藏。
  • 不,它不显示浏览器窗口,它只是保存给定url的png
  • __init__() 和类的定义是什么?
  • 我刚刚编辑了我的帖子,现在你有了带有类定义的代码
  • 是的。我认为这是一个有用的答案(所以请不要删除它),但它在我使用的 Qt 版本中不起作用。
猜你喜欢
  • 2022-10-14
  • 2013-06-15
  • 2010-09-08
  • 2011-10-25
  • 1970-01-01
  • 2010-10-16
  • 2011-01-19
  • 1970-01-01
相关资源
最近更新 更多