问题
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?
回答1:
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_())
来源:https://stackoverflow.com/questions/53330056/pyqt5-pyside2-adblock