Phantomjs / CasperJs没有渲染页面,所以我可以提取链接

时间:2017-11-15 17:22:54

标签: phantomjs casperjs

我在php上使用带有phantomjs的casperjs来提取网页,然后提取任何链接,这样通常所有由javascript创建的链接都会出来,我可以看到它们但不能在这个网站上看到: centralcanadaclassics(。)的COM

这是我正在使用的CasperJS的JS:

var xpath = require('casper').selectXPath;
var casper = require('casper').create({
    pageSettings: {
    loadImages: false,
    webSecurityEnabled: false
    },
    verbose: true,
    logLevel: 'debug',
    colorizerType: 'Dummy'
});

casper.userAgent('casper');
casper.start().then(function() {
    this.open('http://www.centralcanadaclassics.com', {
        headers: {
            'Accept': 'text/html'
        }
     });
});
casper.then(function () {
    this.echo('[CURRENT_URL]' + this.getCurrentUrl());
    this.echo('[CURRENT_TITLE]' + this.getTitle());
    this.echo('[CURRENT_PAGE_CONTENT]' + 
    this.getPageContent().replace(new RegExp('\r?\n','g'), ''));
    this.echo('[CURRENT_HTML]' + this.getHTML().replace(new RegExp('\r? \n','g'), ''));
    this.echo('[CURRENT_HEADERS]' +  JSON.stringify(this.currentResponse.headers));
    this.echo('[CURRENT_STATUS]' + this.currentResponse.status);
    this.echo('[CURRENT_STATUS_TEXT]' + this.currentResponse.statusText);
    this.echo('[CURRENT_COOKIES]' + JSON.stringify(phantom.cookies));
});
casper.run();

所以最后所有内容保持不变,不会呈现该页面。 请解释原因?

1 个答案:

答案 0 :(得分:0)

CasperJS是异步的。您在打开页面时正确地倾销了数据,所以我会在这里继续说谎,并说它正在按照您所说的去做,打开一个页面,虽然它呈现该页面(意思是在它完成之前)尝试使用该内容。

如果有页面内容的JS呈现(动态),您需要实现等待,硬编码延迟(非常脆弱)或识别通常呈现的元素并告诉CapserJS等待它在做任何类型的链接搜索之前看到它。

以下是您使用自己的链接解析外观可能会执行的操作的示例,我将调用它来获取' getLinks()&#39 ;;

// open the page
casper.thenOpen(url).then(function() {
    if (this.exists('#some-id')) {
        this.getLinks();   // this is your link hunting function
    }
});

或类似的东西

casper.wait(1000, function() {
    casper.then(function() {
        this.getLinks();   // this is your link hunting function
    });
});

我认为您在呈现之前尝试使用内容。