繁体   English   中英

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

[英]Prevent CSS/other resource download in PhantomJS/Selenium driven by Python

我试图通过阻止下载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();
    }
};

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

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

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

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

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

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

一个名为“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': []})

在那之前,你只会得到一个Can't find variable: page异常。

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

威尔的回答让我走上正轨。 (谢谢Will!)

目前的PhantomJS(1.9.8)包含已经包含watsonmw补丁的Ghostdriver 1.1.0。

您需要下载最新的PhantomJS,执行以下操作(可能需要sudo ):

ln -s path/to/bin/phantomjs  /usr/local/share/phantomjs
ln -s path/to/bin/phantomjs  /usr/local/bin/phantomjs
ln -s path/to/bin/phantomjs  /usr/bin/phantomjs

然后尝试这个:

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': '''
    var page = this; // won't work otherwise
    page.onResourceRequested = function(requestData, request) {
    // ...
}
''', 'args': []})

建议的解决方案对我不起作用,但是这个解决方案有效(它使用driver.execute_script ):

driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.execute_script('''
    this.onResourceRequested = function(request, net) {
        console.log('REQUEST ' + request.url);
    };
''')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM