How to set up AdBlock in PySide6 Web Browser?

165 Views Asked by At

I'm making a web browser using Python and PySide6. I wanted to set up adblocking on this browser. I know it has to be done with a request interceptor, but I cannot figure out how to do it.

I have some code that doesn't work like it should:

from adblockparser import AdblockRules

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

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

interceptor = WebEngineUrlRequestInterceptor()
QtWebEngineWidgets.QWebEngineProfile.defaultProfile().setRequestInterceptor(interceptor)

Could anyone link me up to some resources or help me out by editing my code?

I tried reading the docs and edited the code multiple times but it didn't work.

I expect the code to intercept requests to any of the 'ad sites' mentioned in easylist.txt

1

There are 1 best solutions below

3
Hamza65523 On

Also check this link. PyQt5/PySide2 AdBlock

pip install adblock

import adblock

class MyWebBrowser(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.web_view = QWebEngineView(self)
        self.web_page = MyWebEnginePage(self.web_view)
        self.web_page.urlChanged.connect(self.on_url_changed)
        self.web_view.setPage(self.web_page)
        self.web_view.load(QUrl("https://example.com"))
        layout = QVBoxLayout(self)
        layout.addWidget(self.web_view)
        self.setLayout(layout)

def on_url_changed(self, url):
    if adblock.should_block(url.toString()):
        self.setHtml("<html><body>Blocked an ad.</body></html>")
    else:
        self.load(url)