I have a working script that uses PyQt-5.5.1, which I now want to port to a new PyQt version (5.7). Adapting most of the things was fine, but I faced two major problems: (1) to perform a (simulated) mouseclick, (2) to access (let's say: print) the html source-code of a webpage which is currently displayed in the QWebView or QWebEngineView, respectively.
For example, I could 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 am aware of the docs as well as this page about porting to QWebEngineView but unable to convert C++ notation to a working Python code.
How can I adapt this to QWebEngineView in PyQt-5.7? Below is a fully working snippet for PyQt-5.5.1, which fails for the new PyQt-version:
- for Button1: no mouse click reaction at all.
- for Button2:
AttributeError: 'QWebEnginePage' object has no attribute 'mainFrame'
, and when I delete 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_STRif 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_())
self.wvTest.setZoomFactor(0.8)
? (2) How can I save the html-code to a string for further processing rather than printing it? Sorry, I'm not familiar with callback-stuff at all. – Gombach