PyQt5/PySide2 AdBlock

∥☆過路亽.° 提交于 2021-02-16 15:04:27

问题


I am trying to create a floating browser for youtube and other media.
I found some old examples of adblock like for PyQt4/PySide but now they are deprecated and I can't translate them to PySide2 QWebEngineView.

Any ideas of how insert the adblock inside a QWebEngineView?

Older version link How would you adblock using Python?


回答1:


To filter urls, a QWebEngineUrlRequestInterceptor must be implemented, and if you want to block the url you must call the block (True) function to the QWebEngineUrlRequestInfo. For filtering I will use the adblockparser library and the 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_())


来源:https://stackoverflow.com/questions/53330056/pyqt5-pyside2-adblock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!