Python - how to use mainframe() method in QWebEnginePage [error of mainframe()]

4167 views python
-3

I am getting error in PyQt5 code. Can any one help me.

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

Output: [Error]

  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'

answered question

1 Answer

1

It seems that you are using a Qt Webkit guide that is deprecate from Qt 5.6, it is currently used Qt WebEngine that has changed many classes and methods since it is based on chromium, in this link you can find a guide how to port Qt Webkit to Qt WebEngine . In your case there is no mainFrame(), and the way to get HTML is asynchronous:

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

posted this

Have an answer?

JD

Please login first before posting an answer.