如何在pyqt5.13中正确使用setHttpUserAgent

2024-09-29 23:23:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做PyQt5,我的版本是5.13。在文档中

https://doc-snapshots.qt.io/qtforpython-dev/PySide2/QtWebEngineWidgets/QWebEngineProfile.html#PySide2.QtWebEngineWidgets.PySide2.QtWebEngineWidgets.QWebEngineProfile.setHttpUserAgent

webview = QWebEngineView()
agent = u"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246"
profile = QWebEngineProfile.setHttpUserAgent(agent)
webpage = QWebEnginePage(profile, webview)
webview.setPage(webpage)
webview.show()

根据上面的文档链接,用户代理字符串类型是Unicode,这是创建的,但是当我运行代码时,出现了错误

profile = QWebEngineProfile.setHttpUserAgent(agent)
TypeError: setHttpUserAgent(self, str): first argument of unbound method must have type 'QWebEngineProfile'

如何解决这种类型错误?据我所知,它们不是QWebEngineProfile类型的字符串


Tags: 字符串文档https版本类型错误profilepyqt5
1条回答
网友
1楼 · 发布于 2024-09-29 23:23:45

试试看:

import sys
from PyQt5.QtCore    import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage


class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.webview = QWebEngineView()
        webpage = QWebEnginePage(self.webview)

        self.useragent = QWebEngineProfile(self.webview)

        agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246"
        self.useragent.defaultProfile().setHttpUserAgent(agent)

        self.webview.setPage(webpage)
        self.webview.setUrl(QUrl("http://whoer.net/"))

        self.setCentralWidget(self.webview)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())         

enter image description here

相关问题 更多 >

    热门问题