QtWebKit:能否获取网页下载文件的事件?
我在这方面遇到了一些困难,简单来说,就是在QWebView中加载一个页面时,能否获取到在渲染页面过程中加载的内容的事件?
我正在使用PySide,所以假设你已经有一个名为'w'的QWebView。
w.load('http://www.unicorns-are-awesome.com/index.html')
而这个index.html的内容看起来是这样的:
<html>
...
<head>
<script src="something.js">
</head>
<body>
<img src="unicorns.jpg">
</body>
</html>
QWebView需要下载something.js和unicorns.jpg这两个文件,但目前似乎没有明显的方法可以获取这些子下载的下载请求事件。
只有在你更改QtWebView中的URL时,w.page()才会发出'downloadRequest'事件,也就是说,你只能获得在'位置'栏中会显示的内容的更新。
那么,如何才能在你的QtWebView中获得网页下载的每一个元素的通知呢?
更新:NetworkAccessManager实现:
from MainWindow import MainWindow
from PySide.QtGui import QApplication
from PySide.QtCore import QCoreApplication
from PySide.QtWebKit import QWebView, QWebSettings
from PySide.QtNetwork import QNetworkReply
class TransferMonitor(object):
def __init__(self):
a = MainWindow._instance # "singleton"
b = a.findChild(QWebView, "browser")
nm = b.page().networkAccessManager()
nm.finished[QNetworkReply].connect( self.dump_url )
def dump_url(self, reply):
# This is probably unnecessary, but
# I wanted to be 100% sure that every get
# was 'fresh'.
QWebSettings.clearMemoryCaches()
# For now all we really do is just dump URLs
# as they're processed. Perhaps later we will intercept.
print reply.url().toString()
1 个回答
1
你需要实现一个叫做QNetworkAccessManager的东西,重写createRequest()这个方法,然后调用QWebPage::setNetworkAccessManager()。我不太确定在PySide中这样做是否可行。