如何使用QWebEngineView和QUrl下载CSV文件

时间:2019-05-03 05:50:02

标签: python pyqt pyqt5 qwebengineview qurl

我正在构建一个程序,该程序使用QWebEngineViewQUrl在我的PyQt5应用程序中运行网站(在Windows 10上运行)。但是,我现在希望能够从同一个网站下载CSV文件,但是作为菜鸟,我似乎不知道该怎么做。

我熟悉使用requestsurllib.requesturllib3等来下载文件,但是为此,我特别想以QWebEngineView的身份来执行此操作将先前在pyqt5窗口中对请求进行身份验证。 首先显示该网站的代码如下:

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

有人对如何实现这一目标有任何建议吗?

1 个答案:

答案 0 :(得分:3)

默认情况下,在QWebEngineView中不处理下载,要启用该功能,您必须使用QWebEngineProfile的downloadRequested信号,这将传输一个QWebEngineDownloadItem,如果您要开始下载,则必须接受:

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

如果要直接下载,可以使用QWebEnginePage的下载方法:

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

更新

@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")