PyQt5:如何下载QWebEngineView的图标?

问题描述 投票:0回答:1

我一直在努力解决像用 PyQt5 的

favicon.ico
显示
QWebEngineView
这样简单的事情。

跟踪和测试服务器都告诉我

pixmap
已下载,但它根本不显示。相反,如果我用本地文件名替换
pixmap
,它就会显示。

我在这里检查了类似的问题,但所有答案似乎都不起作用。 因此,请仅发布经过测试的答案。谢谢!

from PyQt5.Qt import *
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QApplication

url_web = 'https://hamwaves.com/swx/index.html'
url_ico = 'https://hamwaves.com/swx/favicon.ico'

class Browser(QWebEngineView):

    def __init__(self):
        QWebEngineView.__init__(self)

        self.nam = QNetworkAccessManager()
        self.nam.finished.connect(self.set_icon)
        self.nam.get(QNetworkRequest(QUrl(url_ico)))

    def set_icon(self, response):
        pixmap = QPixmap()
        pixmap.loadFromData(response.readAll(), format='ico')
        self.setWindowIcon(QIcon(pixmap))

app = QApplication(sys.argv)
web = Browser()
web.load(QUrl(url_web))
web.show()
sys.exit(app.exec_())
python python-3.x pyqt5 favicon qwebengineview
1个回答
0
投票

请务必检查您收到的内容。

如果你只是做一个

print(response.readAll()
),你会看到这个:

<head><title>Not Acceptable!</title></head><body>
<h1>Not Acceptable!</h1><p>
An appropriate representation of the requested resource could not be 
found on this server. This error was generated by Mod_Security.
</p></body></html>

重新格式化以提高可读性

这对于一般的“匿名”网络请求来说很常见,原因是 QNetworkAccessManager 本身没有设置任何用户代理字符串,并且许多 Web 服务器会忽略此类请求作为基本安全措施和部分流量限制:只有浏览器才能进行请求,他们通常使用正确的用户代理。

只需使用通用用户代理字符串并在发送请求之前调用

setHeader()
。你可以从这里得到一些

request = QNetworkRequest(QUrl(url_ico))
request.setHeader(request.UserAgentHeader, 
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
)
self.nam.get(request)

实际上,这一切都不是必需的,因为 QWebEngineView 已经支持该功能,因此您只需将

iconChanged
信号连接到相关函数即可:

class Browser(QWebEngineView):
    def __init__(self):
        super().__init__()
        self.iconChanged.connect(self.setWindowIcon)

使用上面的网址进行测试时,它会在页面加载后立即正确设置图标,因此根本不需要使用 QNetworkAccessManager。

© www.soinside.com 2019 - 2024. All rights reserved.