我正在尝试为YouTube和其他媒体创建一个浮动浏览器。
我发现了adblock的一些旧示例,例如PyQt4 / PySide,但现在已弃用,无法将其翻译为PySide2 QWebEngineView。

关于如何在QWebEngineView中插入adblock的任何想法?

旧版本链接How would you adblock using Python?

最佳答案

要过滤URL,必须实现QWebEngineUrlRequestInterceptor,如果要阻止URL,则必须对QWebEngineUrlRequestInfo调用阻止(True)函数。为了进行过滤,我将使用adblockparser库和easylist.txt

from PyQt5 import QtCore, QtWidgets, QtWebEngineCore, QtWebEngineWidgets
from adblockparser import AdblockRules

with open("easylist.txt") as f:
    raw_rules = f.readlines()
    rules = AdblockRules(raw_rules)

class WebEngineUrlRequestInterceptor(QtWebEngineCore.QWebEngineUrlRequestInterceptor):
    def interceptRequest(self, info):
        url = info.requestUrl().toString()
        if rules.should_block(url):
            print("block::::::::::::::::::::::", url)
            info.block(True)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    interceptor = WebEngineUrlRequestInterceptor()
    QtWebEngineWidgets.QWebEngineProfile.defaultProfile().setRequestInterceptor(interceptor)
    view = QtWebEngineWidgets.QWebEngineView()
    view.load(QtCore.QUrl("https://www.youtube.com/"))
    view.show()
    sys.exit(app.exec_())

关于python - PyQt5/PySide2 AdBlock,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53330056/

10-12 21:12