提问人:James 提问时间:4/6/2023 更新时间:4/6/2023 访问量:97
如何在PySide6 Web浏览器中设置AdBlock?
How to set up AdBlock in PySide6 Web Browser?
问:
我正在使用 Python 和 PySide6 制作一个 Web 浏览器。 我想在这个浏览器上设置广告拦截。我知道它必须使用请求拦截器来完成,但我无法弄清楚该怎么做。
我有一些代码不能正常工作:
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)
任何人都可以将我链接到一些资源或通过编辑我的代码来帮助我吗?
我尝试阅读文档并多次编辑代码,但没有奏效。
我希望代码能够拦截对easylist.txt中提到的任何“广告网站”的请求
答:
-1赞
Hamza65523
4/6/2023
#1
另请查看此链接。PyQt5/PySide2 广告块
pip 安装 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)
评论
0赞
James
4/7/2023
当我根据需要进行修改来运行它时,adblock 没有一个名为 should_block 的属性。
0赞
musicamante
4/7/2023
这显然不是一个有效的解决方案,因为它会根据页面的 url 阻止内容,但广告可能会在框架中或通过 javascript 加载。此外,它仅在 url 更改后立即起作用,这可能不会发生在内部内容中。
0赞
James
4/7/2023
完全。我正在尝试拦截请求而不是 URL。为了阻止整个 URL,可以使用更小的代码。
评论
WebEngineUrlRequestInterceptor