我在PyQt5代码中遇到错误。谁能帮我。

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView

class Browser(QWebView):

    def __init__(self):
        QWebView.__init__(self)
        self.loadFinished.connect(self._result_available)

    def _result_available(self, ok):
        frame = self.page().mainFrame()
        print( unicode(frame.toHtml()).encode('utf-8'))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = Browser()
    view.load(QUrl('http://www.google.com'))
    app.exec_()


输出:[错误]

  AttributeError                            Traceback (most recent call last)
  <ipython-input-50-e1b5f3fc9054> in _result_available(self, ok)

   13

   14     def _result_available(self, ok):

  ---> 15              frame = self.page().mainFrame()    ------------- [ERROR]

   16         print( unicode(frame.toHtml()).encode('utf-8'))

   17

  AttributeError: 'QWebEnginePage' object has no attribute 'mainFrame'

最佳答案

看来您使用的是Qt 5.6弃用的Qt Webkit指南,当前使用的Qt WebEngine由于基于铬而更改了许多类和方法,在此link中,您可以找到如何移植的指南Qt Webkit到Qt WebEngine。在您的情况下,没有mainFrame(),并且获取HTML的方法是异步的:

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView

class Browser(QWebView):
    def __init__(self):
        QWebView.__init__(self)
        self.loadFinished.connect(self._result_available)

    def _result_available(self, ok):
        if ok:
            frame = self.page()
            frame.toHtml(self.callback)

    def callback(self, html):
        print(unicode(html).encode('utf-8'))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = Browser()
    view.load(QUrl('http://www.google.com'))
    sys.exit(app.exec_())

关于python - Python-如何在QWebEnginePage中使用mainframe()方法[mainframe()错误),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53221011/

10-14 14:53
查看更多