Python-如何在QWebEnginePage中使用mainframe()方法[mainframe()错误]

时间:2018-11-09 06:45:33

标签: python python-3.x pyqt pyqt5 qtwebengine

我在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'

1 个答案:

答案 0 :(得分:1)

似乎您使用的是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_())