-1

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

James
  • 1
  • 1
  • Your code is invalid because `WebEngineUrlRequestInterceptor` should be a subclass of QObject, while right now it's just a basic python object. – musicamante Apr 06 '23 at 15:48
  • Requests for libraries and other resources are off-topic, see [help/on-topic]. "didn't work" is not a helpful problem description. Which code did you run, what happened, and what did you expect to happen instead? Any errors? See [ask]. – Robert Apr 06 '23 at 18:25

1 Answers1

-1

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)
Hamza65523
  • 12
  • 2
  • When I run this with modifications to my need, adblock doesn't have a attribute called should_block. – James Apr 06 '23 at 16:43
  • That is clearly not a valid solution, because it will block the contents based on the url of the page, but the ads may be loaded in frames or by javascript. Also, it works only as soon as the url is changed, which might not happen for internal contents. – musicamante Apr 06 '23 at 17:02
  • Exactly. I'm trying to intercept requests instead of URLs. For blocking entire URLs there can be way smaller code. – James Apr 06 '23 at 17:13