本文介绍了PySide QWebView 和下载不受支持的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是使用 PySide 演示 web 应用程序等的最小浏览器的代码.虽然我似乎不太明白如何成功下载不受支持的内容,但它通常会按照我的意愿运行.
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.
在 Finished 方法中 self.reply.readAll() 返回一个空的 QByteArray.
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_())
推荐答案
在一些帮助下找到了解决方案.有兴趣的朋友,下载的最终版本和完成的功能如下:
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()
这篇关于PySide QWebView 和下载不受支持的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!