我正在努力在使用 PyQt6 制作的自定义浏览器中实现下载处理功能。我在测试这两次下载之间未更改任何代码时遇到了两次下载尝试和两个错误。
我在这里上课:
class DownloadManagerWidget(QWidget):
def downloadRequested(self, download: QWebEngineDownloadRequest):
assert download and download.state() == QWebEngineDownloadRequest.DownloadRequested
# Prompt the user for a file name
path, _ = QFileDialog.getSaveFileName(self, "Save as", QDir(download.downloadDirectory()).filePath(download.downloadFileName()))
if path.isEmpty():
return
# Set download directory and file name
download.setDownloadDirectory(QFileInfo(path).path())
download.setDownloadFileName(QFileInfo(path).fileName())
download.accept()
# Add the download to the download manager
self.add(DownloadWidget(download))
# Show the download manager
self.show()
这是相关下载代码,位于
__init__
的class MainWindow(QMainWindow)
:
self.download_manager_widget = DownloadManagerWidget()
self.download_manager_widget.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False)
QWebEngineProfile.defaultProfile().downloadRequested.connect(self.download_manager_widget.downloadRequested)
尝试从 download.cnet.com 下载文件,我收到此错误:
js:从源“https://download.cnet.com”访问“https://684d0d47.akstat.io/”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于所请求的资源中。
然后,我尝试了另一个(如果我没记错的话,下载 Chrome):
回溯(最近一次调用最后一次): 文件“D:\mybrowser.py”,第 14 行,位于 downloadRequested 中 断言下载和 download.state() == QWebEngineDownloadRequest.DownloadRequested ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError:类型对象“QWebEngineDownloadRequest”没有属性“DownloadRequested”
我很困惑。你能指导我弄清楚我应该做什么吗?基于CORS策略错误,我以为代码没有错误,但是当弹出AttributeError时,这是否意味着代码中存在错误?
PyQt5 从 WebEngineView 下载文件
from PyQt5.QtWebEngineWidgets import QWebEngineProfile as profile
profile.defaultProfile().downloadRequested.connect(self.download_file)
功能download_file
import PyQt5.QtWebEngineWidgets import QWebEngineDownloadItem
def download_file(self, download:QWebEngineDownloadItem):
assert download and download.state() == QWebEngineDownloadItem.DownloadRequested
path, _ = QFileDialog.getSaveFileName(self, "Save as", QDir(download.downloadDirectory()).filePath(download.downloadFileName()))
# File Not Selected close the progress
if path == None:
return
# Set download directory and file name
download.setDownloadDirectory(QFileInfo(path).path())
download.setDownloadFileName(QFileInfo(path).fileName())
# Start Download the file
download.accept()