【问题标题】:Phantomjs/CasperJs not rendering page so i can extract linksPhantomjs/CasperJs 不呈现页面,所以我可以提取链接
【发布时间】:2017-11-15 17:22:53
【问题描述】:

我在 php 上使用 casperjs 和 phantomjs 在提取任何链接之前呈现网页,这样通常所有由 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();

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

【问题讨论】:

  • 那么,您想提取该页面上的所有链接吗?还有你疑惑为什么在 casperjs 输出中看不到链接,而在普通浏览器中却可以看到?

标签: phantomjs casperjs


【解决方案1】:

CasperJS 是异步的。您在打开页面时正在转储您的数据,所以我要在这里冒个泡,说它正在按照您的要求做,打开一个页面,并在渲染该页面时(意思是之前它完成)尝试使用内容。

如果页面内容有 JS 渲染(动态),你需要实现等待,要么是硬编码延迟(非常脆弱),要么识别一个通常渲染的元素并告诉 CapserJS 等待直到它看到它,在进行任何类型的链接搜索之前。

这是一个示例,说明您可以使用自己的链接解析外观来执行什么操作,我将其称为“getLinks()”;

// 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
    });
});

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

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多