2

以下是使用 PySide 演示 webapps 等的最小浏览器的代码。它通常可以按我的意愿运行,但我似乎不太了解如何成功下载 unsupportedContent。

在 Finished 方法中,self.reply.readAll() 返回一个空的 QByteArray。

任何帮助将不胜感激。谢谢

import sys
import os
from PySide import QtCore, QtGui, QtWebKit, QtNetwork


class Browser(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.web = QtWebKit.QWebView()
        self.web.page().setForwardUnsupportedContent(True)
        self.web.page().unsupportedContent.connect(self.download)

        self.manager = QtNetwork.QNetworkAccessManager()
        self.manager.finished.connect(self.finished)

    def download(self, reply):
        self.request = QtNetwork.QNetworkRequest(reply.url())
        self.reply = self.manager.get(self.request)

    def finished(self):
        path = os.path.expanduser(os.path.join('~', unicode(self.reply.url().path()).split('/')[-1]))
        destination = QtGui.QFileDialog.getSaveFileName(self, "Save", path)
        if destination:
            filename = destination[0]
            with open(filename, 'wb') as f:
                f.write(str(self.reply.readAll()))
                f.close()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    browser = Browser()
    browser.web.load(QtCore.QUrl('http://127.0.0.1:8000'))
    browser.web.show()

    sys.exit(app.exec_())
4

1 回答 1

4

在相当多的帮助下找到了解决方案。感兴趣的朋友可以看看最终版本的下载和完成功能如下:

def download(self, reply):
    self.request = reply.request()
    self.request.setUrl(reply.url())
    self.reply = self.manager.get(self.request)

def finished(self):
    path = os.path.expanduser(
        os.path.join('~',
                     unicode(self.reply.url().path()).split('/')[-1]))
    if self.reply.hasRawHeader('Content-Disposition'):
        cnt_dis = self.reply.rawHeader('Content-Disposition').data()
        if cnt_dis.startswith('attachment'):
            path = cnt_dis.split('=')[1]

    destination = QtGui.QFileDialog.getSaveFileName(self, "Save", path)
    if destination:
        f = open(destination[0], 'wb')
        f.write(self.reply.readAll())
        f.flush()
        f.close()
于 2012-07-13T16:58:14.833 回答