How to download csv file with QWebEngineView and QUrl

廉价感情. 提交于 2021-01-24 09:11:13

问题


I'm building a program which uses QWebEngineView and QUrl to display a website in my PyQt5 app (running on Windows 10). However, I now want to be able to download a CSV file from the same website, but being a noob I can't seem to figure out how.

I'm familiar with using requests, urllib.request, urllib3, etc. for downloading files, but for this, I specifically want to do it with the QWebEngineView, as the user will have authenticated the request previously in the pyqt5 window. The code to show the website in the first place goes like this:

self.view = QWebEngineView(self)
self.view.load(QUrl(url))
self.view.loadFinished.connect(self._on_load_finished)
self.hbox.addWidget(self.view)

Does anyone have any suggestion on how this can be achieved?


回答1:


In QWebEngineView by default the downloads are not handled, to enable it you have to use the downloadRequested signal of QWebEngineProfile, this transports a QWebEngineDownloadItem that you have to accept if you want the download to start:

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        QtWebEngineWidgets.QWebEngineProfile.defaultProfile().downloadRequested.connect(
            self.on_downloadRequested
        )

        self.view = QtWebEngineWidgets.QWebEngineView()
        url = "https://domain/your.csv"
        self.view.load(QtCore.QUrl(url))
        hbox = QtWidgets.QHBoxLayout(self)
        hbox.addWidget(self.view)

    @QtCore.pyqtSlot("QWebEngineDownloadItem*")
    def on_downloadRequested(self, download):
        old_path = download.url().path()  # download.path()
        suffix = QtCore.QFileInfo(old_path).suffix()
        path, _ = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save File", old_path, "*." + suffix
        )
        if path:
            download.setPath(path)
            download.accept()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

If you want to make a direct download you can use the download method of QWebEnginePage:

self.view.page().download(QtCore.QUrl("https://domain/your.csv"))

Update:

@QtCore.pyqtSlot("QWebEngineDownloadItem*")
def on_downloadRequested(self, download):
    old_path = download.url().path()  # download.path()
    suffix = QtCore.QFileInfo(old_path).suffix()
    path, _ = QtWidgets.QFileDialog.getSaveFileName(
        self, "Save File", old_path, "*." + suffix
    )
    if path:
        download.setPath(path)
        download.accept()
        download.finished.connect(self.foo)

def foo(self):
    print("finished")


来源:https://stackoverflow.com/questions/55963931/how-to-download-csv-file-with-qwebengineview-and-qurl

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