防止Python驱动的PhantomJS/Selenium中的CSS /其他资源下载

YPC*_*ble 14 python selenium web-scraping headless-browser phantomjs

我试图通过阻止下载CSS /其他资源来加速Python中的Selenium/PhantomJS webscraper.我需要下载的是img src和alt标签.我发现了这段代码:

page.onResourceRequested = function(requestData, request) {
    if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || requestData['Content-Type'] == 'text/css') {
        console.log('The url of the request is matching. Aborting: ' + requestData['url']);
        request.abort();
    }
};
Run Code Online (Sandbox Code Playgroud)

via:如何控制PhantomJS跳过下载某种资源?

如何/在哪里可以在由Python驱动的Selenium中实现此代码?或者,还有另一种更好的方法来阻止CSS /其他资源下载吗?

注意:我已经找到了如何通过编辑service_args变量来阻止图像下载:

如何在python webdriver中为phantomjs/ghostdriver设置代理?

和

PhantomJS 1.8与python上的Selenium.如何阻止图像?

但是service_args无法帮助我使用像CSS这样的资源.谢谢!

Wil*_*ney 7

一个名为"watsonmw"的大胆的年轻灵魂最近为Ghostdriver 添加了功能(Phantom.js用来与Selenium交互),允许访问需要页面对象的Phantom.js API调用,就像onResourceRequested你引用的那样.

对于不惜一切代价的解决方案,请考虑从源代码构建(开发人员注意到"大约需要30分钟......在现代机器上进行4个并行编译作业")并集成上面链接的补丁.

然后,这个(未经测试的)Python代码应该作为概念证明:

from selenium import webdriver
driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.execute('executePhantomScript', {'script': '''
page.onResourceRequested = function(requestData, request) {
    // ...
}
''', 'args': []})
Run Code Online (Sandbox Code Playgroud)

在那之前,你只会得到一个Can't find variable: page例外.

祝好运!有许多很好的选择,比如在Javascript环境中工作,驱动Gecko,代理等.