在CasperJS或PhantomJS中获取资源内容

在CasperJS或PhantomJS中获取资源内容,phantomjs,casperjs,Phantomjs,Casperjs,我看到CasperJS有一个“download”函数和一个“on resource received”回调,但我在回调中没有看到资源的内容,我不想将资源下载到文件系统 我想抓取资源的内容,以便在脚本中使用它。CasperJS或PhantomJS是否可以这样做?您可以使用Casper.debugHTML()打印HTML资源的内容: var casper = require('casper').create(); casper.start('http://google.com/', functio

我看到CasperJS有一个“download”函数和一个“on resource received”回调,但我在回调中没有看到资源的内容,我不想将资源下载到文件系统


我想抓取资源的内容,以便在脚本中使用它。CasperJS或PhantomJS是否可以这样做?

您可以使用
Casper.debugHTML()
打印HTML资源的内容:

var casper = require('casper').create();

casper.start('http://google.com/', function() {
    this.debugHTML();
});

casper.run();

您还可以使用
casper.getPageContent()
:(可在最新母版中获得)将HTML内容存储在var中根据问题158,我发现在phantomjs稍微成熟之前,这对他们来说是有点头痛

那么你想怎么做?为了实现这一点,我选择了更高一点,并在上抓取了PyMiProxy,下载、安装、设置了它,获取了他们的示例代码,并在proxy.py中实现了这一点

from miproxy.proxy import RequestInterceptorPlugin, ResponseInterceptorPlugin, AsyncMitmProxy
from mimetools import Message
from StringIO import StringIO

class DebugInterceptor(RequestInterceptorPlugin, ResponseInterceptorPlugin):

        def do_request(self, data):
            data = data.replace('Accept-Encoding: gzip\r\n', 'Accept-Encoding:\r\n', 1);
            return data

        def do_response(self, data):
            #print '<< %s' % repr(data[:100])
            request_line, headers_alone = data.split('\r\n', 1)
            headers = Message(StringIO(headers_alone))
            print "Content type: %s" %(headers['content-type'])
            if headers['content-type'] == 'text/x-comma-separated-values':
                f = open('data.csv', 'w')
                f.write(data)
            print ''
            return data

if __name__ == '__main__':
    proxy = AsyncMitmProxy()
    proxy.register_interceptor(DebugInterceptor)
    try:
        proxy.serve_forever()
    except KeyboardInterrupt:
        proxy.server_close()
接下来,我使用指定的代理执行phantomjs

phantomjs --ignore-ssl-errors=yes --cookies-file=cookies.txt --proxy=127.0.0.1:8080 --web-security=no myfile.js
你可能想打开你的安全系统或者诸如此类的,这对我来说是不必要的,因为我现在只抓取了一个来源。现在,您应该看到一堆文本在代理控制台中流动,如果它落在mime类型为“text/x-comma-separated-values”的对象上,它将保存为data.csv。这也将保存所有的标题和所有内容,但如果你已经做到这一点,我相信你可以想出如何弹出这些

另一个细节是,我发现我必须禁用gzip编码,我可以使用zlib从我自己的apache Web服务器中解压缩gzip中的数据,但如果数据来自IIS或类似的版本,解压缩将出错,我不确定这部分是否正确


所以我的电力公司不会给我提供API?好的我们做得很辛苦

没有意识到我可以像这样从文档对象中获取源代码:

casper.start(url, function() {
    var js = this.evaluate(function() {
        return document; 
    }); 
    this.echo(js.all[0].outerHTML); 
});

更多信息。

过去几天来,这个问题一直困扰着我。代理解决方案在我的环境中不是很干净,所以我发现phantomjs的QTNetworking核心在缓存资源时将资源放在了哪里

长话短说,这是我的要点。您需要cache.js和mimetype.js文件:

然后,在调用phantomjs时,只需确保已启用缓存:

phantomjs——磁盘缓存=true test.js

一些注意事项:
我写这篇文章的目的是在不使用代理或拍摄低分辨率快照的情况下获取页面上的图像。QT对某些文本文件资源使用压缩,若对文本文件使用压缩,则必须处理解压缩。此外,我还运行了一个快速测试来获取html资源,它没有解析结果中的http头。但是,这对我很有用,希望其他人也会这么认为,如果您对特定内容类型有问题,请修改它。

谢谢NiKo,我想我不清楚,但我正在查找所有其他资源,而不是html页面。我想将外部css或js文件存储在一个var中,这些资源的内容,这可能吗?只需确保您设置了正确的协议(即http vs https)。。我花了一段时间才发现我试图打开的站点正在从http重定向到https。。这让casperjs(bug?)@iwek看了这个链接,了解更多关于如何将资源保存到磁盘的信息:正如你如何解压所回答的那样?我真的很想知道你是如何解压的。你成功了吗?先生,你是一名骑兵。感谢您的帮助。不再工作了,phantomjs使用sqlite for Cache看起来很棒,但在我的例子中,我有一个动态页面,它由许多对同一url的调用生成,使用不同的POST参数:一旦它返回html容器,然后是PDF文件,然后是图像。。。cache.js getUrlCacheFilename()似乎总是返回相同的缓存文件名(7/3kjh55ig.d)——实际上并不存在
casper.start(url, function() {
    var js = this.evaluate(function() {
        return document; 
    }); 
    this.echo(js.all[0].outerHTML); 
});
//for this to work, you have to call phantomjs with the cache enabled:
//usage:  phantomjs --disk-cache=true test.js

var page = require('webpage').create();
var fs = require('fs');
var cache = require('./cache');
var mimetype = require('./mimetype');

//this is the path that QTNetwork classes uses for caching files for it's http client
//the path should be the one that has 16 folders labeled 0,1,2,3,...,F
cache.cachePath = '/Users/brandon/Library/Caches/Ofi Labs/PhantomJS/data7/';

var url = 'http://google.com';
page.viewportSize = { width: 1300, height: 768 };

//when the resource is received, go ahead and include a reference to it in the cache object
page.onResourceReceived = function(response) {
  //I only cache images, but you can change this
    if(response.contentType.indexOf('image') >= 0)
    {
        cache.includeResource(response);
    }
};

//when the page is done loading, go through each cachedResource and do something with it, 
//I'm just saving them to a file
page.onLoadFinished = function(status) {
    for(index in cache.cachedResources) {
        var file = cache.cachedResources[index].cacheFileNoPath;
        var ext = mimetype.ext[cache.cachedResources[index].mimetype];
        var finalFile = file.replace("."+cache.cacheExtension,"."+ext);
        fs.write('saved/'+finalFile,cache.cachedResources[index].getContents(),'b');
    }
};

page.open(url, function () {
    page.render('saved/google.pdf');
    phantom.exit();
});