如何在PyQt 5.13中正确使用setHttpUserAgent

时间:2019-08-28 15:25:58

标签: python pyqt5

我正在开发PyQt5,我的版本是5.13。在文档

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

<profiles>
  <profile>
    <id>jdk9+</id>
    <activation>
      <jdk>[9,)</jdk>
    </activation>
    <properties>
      <maven.compiler.release>8</maven.compiler.release>
    </properties>
  </profile>
</profiles>

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

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

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

1 个答案:

答案 0 :(得分:0)

尝试一下:

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