Python与Selenium和Firefox Webdri一起使用Adblock

2024-09-27 02:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是通过Python使用Adblock Plus和Selenium。我已经能够让它加载扩展,但默认情况下它不包括默认的过滤器“EasyList”

 from selenium import webdriver
 from time import sleep
 ffprofile = webdriver.FirefoxProfile()
 adblockfile = '/Users/username/Downloads/adblock_plus-2.4-tb+fx+an+sm.xpi'
 ffprofile.add_extension(adblockfile)
 ffprofile.set_preference("extensions.adblockplus.currentVersion", "2.4")
 browser = webdriver.Firefox(ffprofile)
 while(True):
    browser.get("www.cnn.com")
    sleep(5)

大部分代码都是从http://selenium-python.readthedocs.org/en/latest/faq.html中提取出来的


Tags: fromimportbrowser目标selenium情况plussleep
2条回答

有更好的方法:

1)使用7-zip或等效文件提取adblock.xpi

2)使用常规文本编辑器打开/modules/AppIntegration.jsm

3)找到“notifyUser()”的函数声明,并将其替换为一个简单的返回。例如:

/**
* function notifyUser()
* {
*   let wrapper = (wrappers.length ? wrappers[0] : null);
*   if (wrapper && wrapper.addTab)
*   {
*       wrapper.addTab("chrome://adblockplus/content/ui/firstRun.xul");
*   }
*   else
*   {
*       Utils.windowWatcher.openWindow(wrapper ? wrapper.window : null,
*                                                                    "chrome://adblockplus/content/ui/firstRun.xul",
*                                                                    "_blank", "chrome,centerscreen,resizable,dialog=no", null);
*   }
* }
*/

function notifyUser()
{
    return;
}

现在您只需要将文件打包回zip,并将扩展名从.zip改为.xpi——瞧!

这将阻止adblock加载欢迎页面,但仍将配置必要的订阅设置。确保呼叫

ffprofile.set_preference("extensions.adblockplus.currentVersion", "x.x.x")

否则,它将不知道“启动自己”

请注意,这是adblock_plus-2.0.3的,因为我使用的是firefox-17。代码可能略有不同,对于较新版本,可能位于不同的位置。见:https://issues.adblockplus.org/ticket/206#comment:5

实际上,默认情况下,Adblock Plus将添加EasyList,但如果将extensions.adblockplus.currentVersion首选项设置为禁用更新/首次运行操作,则不会添加EasyList。我猜您的目标是阻止第一个运行页面出现,但它也阻止了数据存储初始化。注意,这里有更多的问题:即使Adblock Plus添加了EasyList,下载仍然需要一段未知的时间。

更好的方法应该是使用现有的adblockplus/patterns.ini文件初始化配置文件。您可以使用EasyList和其他过滤器设置从常规Firefox配置文件中获取此文件,并将其复制到/Users/username/Downloads/profilemodel/adblockplus/patterns.ini。那么下面的方法应该有效:

ffprofile = webdriver.FirefoxProfile("/Users/username/Downloads/profilemodel");

相关问题 更多 >

    热门问题