在我的系统上,我目前正在运行Polipo代理,主要是出于广告阻止的目的。通过在互联网上搜索,我发现了许多用于转换Polipo forbidden file format中的adblock和列表的shell脚本;这些脚本大多依赖于sed、ruby或python。但是,它们都不能生成有效的禁用文件:当我用新生成的禁用文件重新启动Polipo时,在Polipo的日志文件中看到消息:"Couldn't compile regex: Unmatched ( or \(“
下面是我尝试使用的python脚本,用于将easylist文件转换为Polipo禁止的文件格式:
#!/bin/python
# convert adblock ruleset into polipo-forbidden format
if __name__ == "__main__":
import os
import sys
import re
if len(sys.argv) == 1:
sys.exit("Usage: %s <adblockrules>" % os.path.basename(sys.argv[0]))
if not os.path.exists(sys.argv[1]):
sys.exit("The rules file (%s) doesn't exist" % sys.argv[1])
fhandle = file(sys.argv[1])
lines = fhandle.readlines()
fhandle.close()
dollar_re = re.compile("(.*?)\$.*")
for line in lines:
if line:
if (line[0] in ("[", "!", "~", "#", "@") or
line.startswith("/adverti") or
"##" in line):
continue
line = dollar_re.sub(r"\1", line)
# line = line.replace("|http://", "")
line = line.replace("|", "")
line = line.replace("||", "")
line = line.replace(".", r"\.")
line = line.replace("*", ".*")
line = line.replace("?", r"\?")
line = line.replace("^", r"[\/:\.=&\?\+\-\ ]+")
# line = line.replace("&", r"\&")
# line = line.replace("+", r"\+")
# line = line.replace("-", r"\-")
# line = line.replace(";", r"\;")
# line = line.replace("=", r"\=")
# line = line.replace("/", r"\/")
print(line.strip())
print("")但是正如我已经说过的,当我实现这个被禁止的文件时,Polipo将声明"Couldn't compile regex: Unmatched ( or \(“
这是由script http://wikisend.com/download/494664/forbidden.conf生成的禁用文件
正如我已经说过的,网上有许多像我使用的脚本,其中一些也依赖于sed,但似乎没有人能够生成有效的禁用文件(Polipo总是声称“无法编译regex")。这不是Polipo的错,因为如果我创建了一个包含一些web url的干净的禁用文件,Polipo将正确地阻止这些连接。
有人能帮我解释一下如何修改/制作一个合适的脚本来将adblock列表转换为Polipo的有效regex禁用文件吗?
非常感谢。
发布于 2016-10-19 03:21:53
您可以使用https://github.com/scrapinghub/adblockparser库将广告阻止规则转换为Python regex:
>>> from adblockparser import AdblockRule
>>> rule = AdblockRule("/ad/loaders/*")
>>> print(rule.regex)
/ad/loaders/.*我不确定Polipo是否支持相同的正则表达式格式;正则表达式可能会变得非常复杂:
>>> print(AdblockRule("||example.com$").regex)
^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?example\.com还要注意带有选项的规则;删除它们可能更好,因为语义是不同的。
希望这能有所帮助。
https://stackoverflow.com/questions/35262685
复制相似问题