PySide QWebView and downloading unsupported content

ぃ、小莉子 提交于 2019-12-11 04:25:18

问题


Below is the code for a minimal browser using PySide for demoing webapps and the like. It generally functions as I'd like though I can't quite seem to get my head around how to successfully download unsupportedContent.

In the Finished method self.reply.readAll() returns an empty QByteArray.

Any help would be greatly appreciated. Thanks

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_())

回答1:


With a fair bit of help a solution was found. For those who might be interested, the final versions of the download and finished function are as follows:

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()


来源:https://stackoverflow.com/questions/11043807/pyside-qwebview-and-downloading-unsupported-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!