简体   繁体   中英

How to download csv file with QWebEngineView and QUrl

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?

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)

        self.view = QtWebEngineWidgets.QWebEngineView()
        self.view.page().profile().downloadRequested.connect(
            self.on_downloadRequested
        )
        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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM