【发布时间】:2016-10-11 18:28:32
【问题描述】:
如何使用 PyQt5 v5.6 QWebEngineView “渲染” HTML?
我之前使用 PyQt5 v5.4.1 QWebPage 执行过任务,但尝试更新的 QWebEngineView 是 suggested 。
这是该实现(它通常按预期工作,但在某些站点和情况下倾向于无限期挂起):
def render(source_html):
"""Fully render HTML, JavaScript and all."""
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebKitWidgets import QWebPage
class Render(QWebPage):
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()
return Render(source_html).html
import requests
sample_html = requests.get(dummy_url).text
print(render(sample_html))
接下来是我使用 QWebEngineView 的尝试。一、PyQt5 v5.6在Ubuntu上的安装设置:
# install PyQt5 v5.6 wheel from PyPI
pip3 install --user pyqt5
# link missing resources
ln -s ../resources/icudtl.dat ../resources/qtwebengine_resources.pak ../resources/qtwebengine_resources_100p.pak ../resources/qtwebengine_resources_200p.pak ../translations/qtwebengine_locales ~/.local/lib/python3.5/site-packages/PyQt5/Qt/libexec/
现在对于 Python... 以下结果会导致分段错误:
def render(source_html):
"""Fully render HTML, JavaScript and all."""
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
class Render(QWebEngineView):
def __init__(self, html):
self.html = None
self.app = QApplication(sys.argv)
QWebEngineView.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.setHtml(html)
self.app.exec_()
def _loadFinished(self, result):
# what's going on here? how can I get the HTML from toHtml?
self.page().toHtml(self.callable)
self.app.quit()
def callable(self, data):
self.html = data
return Render(source_html).html
import requests
sample_html = requests.get(dummy_url).text
print(render(sample_html))
问题似乎在于对异步toHtml() 的调用。看起来它应该相当简单,但我不知道如何处理它。我看到它在 C++ 的上下文中是 discussed,但我不知道如何将它翻译成 Python。我怎样才能得到 HTML?
【问题讨论】: