Search code examples
pythonpyqt5html-to-pdf

QtWebEngineWidgets importError


I tried using the following code to convert webpage to pdf file:

import sys
from PyQt5 import QtWebEngineWidgets, QtCore, QtWidgets

app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(
    lambda *args: print('finished:', args))
loader.load(QtCore.QUrl('https://en.wikipedia.org/wiki/Main_Page'))

def emit_pdf(finished):
    loader.show()
    loader.page().printToPdf("test.pdf")

loader.loadFinished.connect(emit_pdf)

app.exec()

But I received the error below:

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py", line 2, in <module>
    from PyQt5 import QtWebEngineWidgets, QtCore, QtWidgets
ImportError: cannot import name 'QtWebEngineWidgets' from 'PyQt5' (/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.8/site-packages/PyQt5/__init__.py)

Solution

  • You may try running it on Python 3.7, if you are using a version later than that. (I've been having this exact error despite following the "fixes" in other posts, but once I used Python 3.7 and PyQt5==5.15.0 my application ran without issue.)