使用PyQt4返回Javascript生成的HTML
我正在使用下面这段基础的PyQt4代码,目的是捕捉页面上由JavaScript生成的所有HTML内容:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
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()
def getHtml(str_url):
r_html = Render(str_url)
html = r_html.frame.toHtml()
return html
接着,我创建了一个测试页面来看看这个方法是否有效:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#test').text('This is a test!')
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
所以运行这段代码后,
getHtml('http://www.mytestpage.com')
我本来期待能看到包含“这是一个测试!”文本的HTML在div里显示出来。但是返回的HTML中却没有这部分内容。
我哪里做错了?是代码没有等到页面完全加载吗?还是我对这个用例理解错了?
2 个回答
0
你在 <script src = ...>
的链接中忘记加 http:
了。 (= =" 你怎么不先检查一下呢) 应该是这样的:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
如果你想在 PyQt4 中显示网页,我推荐使用 QtWebKit.QWebView
来展示网页。
这里有个简单的例子:
import sys
from PyQt4 import QtGui, QtCore, QtWebKit
class QCustomWebView (QtWebKit.QWebView):
def __init__ (self, parent = None):
super(QCustomWebView, self).__init__(parent)
# self.load(QtCore.QUrl('https://www.google.jp')) # Test web link
self.load(QtCore.QUrl('hello.html')) # Test html file
self.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, True)
myQApplication = QtGui.QApplication([])
myQCustomWebView = QCustomWebView()
myQCustomWebView.show()
sys.exit(myQApplication.exec_())
注意:hello.html
是你的 HTML 文件。
0
问题是我在系统上没有正确安装PyQt4。重新安装后问题就解决了。唉