1

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?

  • Thanks for the reply @eyllanesc, added the link for the older version. I am reading the docs but nothing so far, it seems the methods were ripped off. I believe they changed the names, the modules and how to implement :( – Maxwell Dalboni Nov 16 '18 at 01:29

1 Answers1

4

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241