导入错误:没有名为QtWebKit的模块
我在使用centos5系统。我通过一个叫做make altinstall的命令安装了python26的源代码。然后我做了以下操作:
yum install qt4
yum install qt4-devel
yum install qt4-doc
我从riverbankcomputing.co.uk网站下载了sip 4.10.2的源代码,编译和安装都很顺利。接着,我又从同一个网站下载并编译了PyQt-x11-4.7.3的源代码。
这两个安装都是用的python26版本(/usr/local/bin/python2.6)。所以configure.py、make和make install这些步骤都没有出错。最后,我尝试运行一个脚本,但遇到了这个帖子标题中的错误:
import sys
import signal
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage
def onLoadFinished(result):
if not result:
print "Request failed"
sys.exit(1)
#screen = QtGui.QDesktopWidget().screenGeometry()
size = webpage.mainFrame().contentsSize()
# Set the size of the (virtual) browser window
webpage.setViewportSize(webpage.mainFrame().contentsSize())
# Paint this frame into an image
image = QImage(webpage.viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
webpage.mainFrame().render(painter)
painter.end()
image.save("output2.png")
sys.exit(0)
app = QApplication(sys.argv)
signal.signal(signal.SIGINT, signal.SIG_DFL)
webpage = QWebPage()
webpage.connect(webpage, SIGNAL("loadFinished(bool)"), onLoadFinished)
webpage.mainFrame().load(QUrl("http://www.google.com"))
sys.exit(app.exec_())
在配置pyqt4的开始,我看到提示说需要安装QtWebKit,但显然它没有安装?这是怎么回事?
我刚刚查了一下,发现QtWebKit确实没有安装。我现在有什么选择呢?
[root@localhost ~]# find / -name '*QtWebKit*'
/root/PyQt-x11-gpl-4.7.3/sip/QtWebKit
/root/PyQt-x11-gpl-4.7.3/sip/QtWebKit/QtWebKitmod.sip
/root/PyQt-x11-gpl-4.7.3/cfgtest_QtWebKit.cpp
5 个回答
2
安装Python模块 PySide
,可以这样做:
pip install PySide
然后把你的导入语句从:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage
改成:
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import QWebPage
另外,你也可以把PySide当作备用方案,这样可以让你的代码在旧系统上也能运行:
try:
# NOTE We need to try importing QtWebKit first,
# because it is the most likely one to not be available,
# and all used QT classes need to come from the same module,
# to be compatible with each other.
from PyQt4.QtWebKit import QWebPage
from PyQt4.QtCore import *
from PyQt4.QtGui import *
except ImportError:
try:
from PySide.QtGui import *
from PySide.QtWebKit import QWebPage
except ImportError:
raise Exception("We require PyQt4 (with QtWebKit) or PySide")
注意 从长远来看,你应该转向QT5,因为上面提到的只是一些临时解决办法。
5
这个命令的意思是用apt工具来安装一个叫做python-pyqt5.qtwebkit的东西。简单来说,apt是一个用来管理软件的工具,而python-pyqt5.qtwebkit是一个Python的库,它可以帮助你在程序中使用网页相关的功能。通过这个命令,你可以把这个库安装到你的电脑上,让你在写Python程序的时候可以用到它。
4
再仔细确认一下,你的系统上安装的Qt是否包含了Webkit这个库。
另外,检查一下在你的python2.6/site-packages/PyQt4目录下,是否有QtWebKit.so这个文件。