我是Python新手,我试图理解为什么我会遇到以下错误:
Traceback (most recent call last):
File "WebScraper.py", line 10, in <module>
class Render(QWebPage):
NameError: name 'QWebPage' is not defined以下是代码:
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from lxml import html
#Take this class for granted.Just use result of rendering.
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
url = 'http://pycoders.com/archive/'
r = Render(url)
result = r.frame.toHtml()
#This step is important.Converting QString to Ascii for lxml to process
archive_links = html.fromstring(str(result.toAscii()))
print(archive_links)我理解__init__充当构造函数,但为什么不将其设置为self?所以我需要把它改成像QWebPage.x = self这样的东西
发布于 2017-01-20 01:52:42
你不能进口QWebPage
尝试将此导入添加到脚本的顶部:
from PyQt5.QtWebKitWidgets import QWebPage发布于 2017-07-29 23:51:17
您使用的是什么版本的PyQt5?请注意,启动PyQt5.9、QtWebKitWidgets (以及QtWebKit)将不再可用(不推荐),从而导致您正在获得的错误。
让我并列两个呈现函数,一个使用旧的(PyQt4),另一个使用最新的PyQt5:
使用PyQt4,注意QWebPage的用法,当然还有导入
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
class Render(QWebPage):
"""Render HTML with PyQt4 WebEngine."""
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()使用PyQt5时,注意使用QWebPage而不是QWebPage,当然还有导入
from PyQt5.QtCore import QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
class Render(QWebEngineView):
"""Render HTML with PyQt5 WebEngine."""
def __init__(self, html):
self.html = None
self.app = QApplication(sys.argv)
QWebEngineView.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.setHtml(html)
while self.html is None:
self.app.processEvents(
QEventLoop.ExcludeUserInputEvents |
QEventLoop.ExcludeSocketNotifiers |
QEventLoop.WaitForMoreEvents)
self.app.quit()https://stackoverflow.com/questions/41754786
复制相似问题