您将如何使用 Python 进行广告拦截? [英] How would you adblock using Python?

查看:93
本文介绍了您将如何使用 Python 进行广告拦截?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PyQt4 中慢慢构建一个 网络浏览器 并且喜欢我的速度正在摆脱它.但是,我想将 easylist.txt 与它结合起来.我相信 adblock 使用它来阻止浏览器的 http 请求.

I'm slowly building a web browser in PyQt4 and like the speed i'm getting out of it. However, I want to combine easylist.txt with it. I believe adblock uses this to block http requests by the browser.

您将如何使用 python/PyQt4 进行处理?

How would you go about it using python/PyQt4?

[edit1] 好的.我想我已经设置了 Privoxy.我没有设置任何额外的过滤器,它似乎工作.我尝试使用的 PyQt4 看起来像这样

[edit1] Ok. I think i've setup Privoxy. I haven't setup any additional filters and it seems to work. The PyQt4 i've tried to use looks like this

self.proxyIP = "127.0.0.1"  
self.proxyPORT= 8118  
proxy = QNetworkProxy()  
proxy.setType(QNetworkProxy.HttpProxy)  
proxy.setHostName(self.proxyIP)  
proxy.setPort(self.proxyPORT)  
QNetworkProxy.setApplicationProxy(proxy)

然而,这绝对没有任何作用,我无法理解文档,也找不到任何示例.

However, this does absolutely nothing and I cannot make sense of the docs and can not find any examples.

[edit2] 我刚刚注意到,如果我将 self.proxyIP 更改为我的实际本地 IP 而不是 127.0.0.1,则页面不会加载.所以有些事情正在发生.

[edit2] I've just noticed that i'f I change self.proxyIP to my actual local IP rather than 127.0.0.1 the page doesn't load. So something is happening.

推荐答案

我知道这是一个老问题,但我想我会尝试为任何偶然发现它的人提供答案.您可以创建 QNetworkAccessManager 的子类,并将其与 https://github.com/atereshkin/abpy 结合使用.有点像这样:

I know this is an old question, but I thought I'd try giving an answer for anyone who happens to stumble upon it. You could create a subclass of QNetworkAccessManager and combine it with https://github.com/atereshkin/abpy. Something kind of like this:

from PyQt4.QtNetwork import QNetworkAccessManager
from abpy import Filter
adblockFilter = Filter(file("easylist.txt"))
class MyNetworkAccessManager(QNetworkAccessManager):
    def createRequest(self, op, request, device=None):
        url = request.url().toString()
        doFilter = adblockFilter.match(url)
        if doFilter:
            return QNetworkAccessManager.createRequest(self, self.GetOperation, QNetworkRequest(QUrl()))
        else:
            QNetworkAccessManager.createRequest(self, op, request, device)
myNetworkAccessManager = MyNetworkAccessManager()

之后,在所有 QWebView 实例上设置以下内容,或者创建 QWebView 的子类:

After that, set the following on all your QWebView instances, or make a subclass of QWebView:

QWebView.page().setNetworkAccessManager(myNetworkAccessManager)

希望这会有所帮助!

这篇关于您将如何使用 Python 进行广告拦截?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆