I have a working script that uses PyQt-5.5.1, which I now want to transfer to the new version of PyQt (5.7). The adaptation of most things was great, but I ran into two serious problems: (1) execute (simulated) mouseclick, (2) access (let’s say: print) the html source code of the webpage that is currently displayed in QWebView or QWebEngineView , respectively.
For example, I can do the following using QWebView in PyQt-5.5.1:
QTest.mouseClick(self.wvTest, Qt.LeftButton, QPoint(x, y))
and
frame = self.wvTest.page().mainFrame()
print(frame.toHtml().encode('utf-8'))
I know docs , as well as this page about porting to QWebEngineView, but unable to convert C ++ notation to working Python code.
How can I adapt this to QWebEngineView in PyQt-5.7? Below is the full excerpt for PyQt-5.5.1, which is not suitable for the new version of PyQt:
- for Button1: no response to a mouse click.
- Button2 to:
AttributeError: 'QWebEnginePage' object has no attribute 'mainFrame', and when I remove the mainframe () TypeError: toHtml(self, Callable[..., None]): not enough arguments.
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QRect, Qt, QUrl, QPoint, QEvent
from PyQt5.QtTest import QTest
from PyQt5.Qt import PYQT_VERSION_STR
if PYQT_VERSION_STR == '5.5.1': from PyQt5 import QtWebKitWidgets else: from PyQt5 import QtWebEngineWidgets
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.button1 = QPushButton('Button1', self)
self.button1.clicked.connect(self.buttonOne)
self.button1.setGeometry(QRect(10, 10, 90, 20))
self.button2 = QPushButton('Button2', self)
self.button2.clicked.connect(self.buttonTwo)
self.button2.setGeometry(QRect(110, 10, 90, 20))
if PYQT_VERSION_STR=='5.5.1': self.wvTest = QtWebKitWidgets.QWebView(self)
else: self.wvTest = QtWebEngineWidgets.QWebEngineView(self)
self.wvTest.setGeometry(QRect(10, 40, 430, 550))
self.wvTest.setUrl(QUrl('http://www.startpage.com'))
self.wvTest.setObjectName('wvTest')
self.setGeometry(300, 300, 450, 600)
self.setWindowTitle('WebView minimalistic')
self.show()
def buttonOne(self):
qp = QPoint(38, 314)
QTest.mouseClick(self.wvTest, Qt.LeftButton, pos=qp) # or: QTest.mouseMove(self.wvTest, pos=self.qp)
print('Button1 pressed.')
def buttonTwo(self):
frame = self.wvTest.page().mainFrame()
print(frame.toHtml().encode('utf-8'))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
source
share