52

phantomjs 有配置 loadImage,

但我想要更多,

如何控制 phantomjs 跳过下载某种资源,

比如css等...

=====

好消息:已添加此功能。

https://code.google.com/p/phantomjs/issues/detail?id=230

要点:

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();
    }
};
4

4 回答 4

17

更新,工作!

自 PhantomJS 1.9 以来,现有答案不起作用。您必须使用此代码:

var webPage = require('webpage');
var page = webPage.create();

page.onResourceRequested = function(requestData, networkRequest) {
  var match = requestData.url.match(/wordfamily.js/g);
  if (match != null) {
    console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
    networkRequest.cancel(); // or .abort() 
  }
};

如果使用 abort() 而不是 cancel(),则会触发 onResourceError。

您可以查看 PhantomJS 文档

于 2015-06-22T11:30:44.343 回答
7

所以最后你可以试试这个http://github.com/eugenehp/node-crawler

否则您仍然可以使用 PhantomJS 尝试以下方法

最简单的方法是加载页面 -> 解析页面 -> 排除不需要的资源 -> 将其加载到 PhatomJS 中。

另一种方法是简单地阻止防火墙中的主机。

或者,您可以使用代理来阻止某些 URL 地址和对它们的查询。

还有一个,加载页面,然后删除不需要的资源,但我认为这不是正确的方法。

于 2012-06-17T20:30:08.347 回答
6

使用page.onResourceRequested,例如loadurlwithoutcss.js

page.onResourceRequested = function(requestData, request) {
    if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || 
            requestData.headers['Content-Type'] == 'text/css') {
        console.log('The url of the request is matching. Aborting: ' + requestData['url']);
        request.abort();
    }
};
于 2015-06-09T12:41:13.750 回答
3

现在没办法(phantomjs 1.7),它不支持。

但是一个讨厌的解决方案是使用 http 代理,这样你就可以屏蔽掉一些你不需要的请求

于 2012-10-25T02:06:11.460 回答