Skip to main content
 首页 » 编程设计

python之QWebEngineView中如何指定用户代理

2024年11月01日40xing901022

我正在使用 PyQt5 在网页上实现自动化功能。 PyQt5 中显示的页面与 Chrome 中显示的页面有很大不同。如果我要更改用户代理,我可以模仿 Chrome 的功能吗?如果是这样,我将如何在以下示例中更改用户代理:

import sys 
from PyQt5.QtCore import * 
from PyQt5.QtWebEngineWidgets import * 
from PyQt5.QtWidgets import * 
 
app = QApplication(sys.argv) 
web = QWebEngineView() 
 
profile = QWebEngineProfile() 
profile.setHttpUserAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36") 
 
# How do i set the profile in the web ??? 
 
web.load(QUrl("https://stackoverflow.com")) 
web.show() 
web.loadFinished.connect(on_load_finished) 
 
sys.exit(app.exec_()) 

请您参考如下方法:

根据 the docs :

The User-Agent request header contains a characteristic string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent.

一些网页会使用User Agent来为您的浏览器显示个性化内容,例如,通过user-agent信息您可以推断它是否支持AJAX。

如果我要更改用户代理,我可以模仿 Chrome 的功能吗?

可能是的,尽管 Google Chrome 和 Qt Webengine 都是基于 Chromium,但是每个开发组都创建了一个新的层,可以具有不同的功能,例如 QtWebEngine 抑制了新版本中添加的许多 Chromium 功能。

我将如何更改用户代理?

无需创建新的 QWebEngineProfile,因为您可以使用页面的配置文件:

import sys 
from PyQt5.QtCore import QUrl 
from PyQt5.QtWebEngineWidgets import QWebEngineView 
from PyQt5.QtWidgets import QApplication 
 
if __name__ == "__main__": 
 
    app = QApplication(sys.argv) 
    web = QWebEngineView() 
 
    print(web.page().profile().httpUserAgent()) 
 
    web.page().profile().setHttpUserAgent( 
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" 
    ) 
    web.load(QUrl("https://stackoverflow.com")) 
    web.show() 
    web.resize(640, 480) 
    sys.exit(app.exec_()) 

如果你想使用 QWebEngineProfile 然后创建一个新的 QWebEnginePage:

import sys 
from PyQt5.QtCore import QUrl 
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineProfile, QWebEngineView 
from PyQt5.QtWidgets import QApplication 
 
if __name__ == "__main__": 
 
    app = QApplication(sys.argv) 
    web = QWebEngineView() 
 
    profile = QWebEngineProfile() 
    profile.setHttpUserAgent( 
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" 
    ) 
 
    page = QWebEnginePage(profile, web) 
    web.setPage(page) 
    web.load(QUrl("https://stackoverflow.com")) 
    web.show() 
    web.resize(640, 480) 
    sys.exit(app.exec_())