使用CasperJS进行刮擦:页面似乎在没有启用javascript的情况下加载

Scraping with CasperJS: page seems to load without javascript enabled

本文关键字:启用 javascript 加载 情况下 CasperJS 使用      更新时间:2023-09-26

我正试图从谷歌上抓取图书类型信息。

就像你在谷歌上进行计算/转换一样,结果会显示在搜索结果上方的框中。我可以很容易地在浏览器(控制台)中抓取这个框中的数据,但是当我在casper中尝试相同的代码时,内容框不会出现在代码中的任何位置。我可以在浏览器中复制这一点的唯一方法是关闭JS

我不知道为什么CasperJS和我自己的浏览器会显示不同的格式,但有没有办法让它们相同?这是我使用的当前代码,其中

链接=https://www.google.com/webhp?hl=en&tab=ww#safe=off&hl=en&output=搜索&sclient=psy ab&q=The+Love+Affairs+of+a+书目狂+书籍+流派&oq=The+Love+Affairs+of

casper.start();
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36        (KHTML, like Gecko) ');
casper.thenOpen(links, function() {
casper.waitForSelector('.answer_predicate', function() {
this.echo(this.getHTML('.answer_predicate'));
});

});
casper.run();
}

运行以下程序:

var casper = require('casper').create({
  pageSettings: {
    loadImages: false,
    loadPlugins: false,
    userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1588.0 Safari/537.36'
  }
});
links = 'https://www.google.com/webhp?hl=en&tab=ww#safe=off&hl=en&output=search&sclient=psy-ab&q=The+Love+Affairs+of+a+Bibliomaniac+book+genre&oq=The+Love+Affairs+of+a+Bibliomaniac+book+genre'
casper.start();
casper.thenOpen(links, function() {
  this.waitForSelector('.answer_predicate', function() {
    this.echo(this.getHTML('.answer_predicate'));
    this.echo(this.getElementInfo('.answer_predicate').text);
  });
});
casper.run();

给我这个输出:

<span class="kno-a-v">Fiction</span>
Fiction

我的假设是,这里的问题与这里发布的问题相同。

@PAEz:试试这个脚本,它与hexd创建的脚本非常相似,但只使用了phantomjs(没有casperjs)。

顺便说一句,既然他先回答了,而我也在做类似的事情,我认为他是应该得到赏金的人。

var page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36';
page.open('https://www.google.com/webhp?hl=en&tab=ww#bav=on.2,or.r_qf.&cad=b&fp=c210d6fe329544e7&hl=en&q=The+Love+Affairs+of+a+Bibliomaniac+book+genre&safe=off', function() {
    window.setTimeout(function() {
        var genre = page.evaluate(function() {
            return document.getElementsByClassName('answer_predicate')[0].textContent;
        });
        console.log(genre);
    }, 3000);
});

我使用的是phantomjs 1.9.1 btw.