在Python 3.5中无法从PyQt5导入QWebPage。

6

我现在正试图编写一些代码来从Java渲染的页面中爬取网络内容。我在网上找到了一些使用PyQt5的示例。然而,当我安装了PyQt5.5.7并尝试导入它的模块时(ImportError:无法导入名称'QWebPage'),失败了。以下是参考代码。非常感谢任何人可以提供解决此问题的建议或其他爬取Java渲染的网页内容的方法。

# standard imports
import sys

# third-party imports
import requests
from bs4 import BeautifulSoup
from pyvirtualdisplay import Display
from PyQt5.QtWebEngineWidgets import QWebPage
from PyQt5.QtWidgets import QApplication



class Render(QWebPage):
    """Render HTML with PyQt5 WebKit."""

    def __init__(self, html):
        self.html = None
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().setHtml(html)
        self.app.exec_()

    def _loadFinished(self, result):
        self.html = self.mainFrame().toHtml()
        self.app.quit()


url = 'https://impythonist.wordpress.com/2015/01/06/ultimate-guide-for-scraping-javascript-rendered-web-pages/'

# get the raw HTML
source_html = requests.get(url).text

# return the JavaScript rendered HTML
with Display(visible=0, size=(800, 600)):
    rendered_html = Render(source_html).html

# get the BeautifulSoup
soup = BeautifulSoup(rendered_html, 'html.parser')

print('title is %r' % soup.select_one('title').text)
2个回答

5

QWebPage是PyQt4中QtWebKit模块中的一个类。该模块已被弃用,并作为PyQt5的可选附加组件分离出来。安装方法如下:

pip install PyQtWebEngine

QtWebKit已被QtWebEngineWidgets取代,相应的类取代QWebPage是QWebEnginePage。因此,你应该这样说:

from PyQt5.QtWebEngineWidgets import QWebEnginePage

-1

尝试使用以下代码:

from PyQt5.QtWebKitWidgets import QWebView,QWebPage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接