我正在构建一个网络浏览器,我想在其中启用广告拦截功能。 我已经阅读了多个答案,但我还没有成功实现它。
我已成功加载adFilter,广告匹配工作正常。
我认为这与networkAccessManager有关,但我无法弄清楚如何。
这是我继承QNetworkAccessManager类的类
class NetworkManager(QNetworkAccessManager):
def __init__(self):
super().__init__()
self.adblocker = Filter(open('easylist.txt', encoding="utf8"))
self.finished.connect(self._finished)
def createRequest(self, op, request, device=None):
url = request.url().toString()
if self.adblocker.match(url):
print('blocking url, ', url)
# block ads here
else:
print('good to go', url)
return QNetworkAccessManager.createRequest(self, op, request, device)
def examine(self, url):
self.get(QNetworkRequest(QUrl(url)))
def _finished(self, reply):
headers = reply.rawHeaderPairs()
headers = {str(k):str(v) for k,v in headers}
content_type = headers.get("Content-Type")
url = reply.url().toString()
status = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
cookies = headers.get("Set-Cookie")
logger.log('{} --- {} --- {}'.format(str(status), url, content_type), 2)
我尝试重写createRequest方法。广告已被检测到,但这些广告请求实际上并未被屏蔽。
我如何实现这一目标。
答案 0 :(得分:0)
这就是我最终实现AdBlocker的方式。您只需要覆盖QWebEnginePage类中的acceptNavigationRequest方法。这就是我实现它的方式
class WebPage(QWebEnginePage):
adblocker = Filter(open('easylist.txt', encoding="utf8"))
def __init__(self, parent=None):
super().__init__(parent)
def acceptNavigationRequest(self, url, _type, isMainFrame):
urlString = url.toString()
resp = False
resp = WebPage.adblocker.match(url.toString())
if resp:
print("Blocking url --- "+url.toString())
return False
else:
print("TYPE", _type)
return True
return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)