【问题标题】:PhantomJS and CasperJS clicking a link and get htmlPhantomJS 和 CasperJS 单击链接并获取 html
【发布时间】:2015-11-19 16:00:03
【问题描述】:

我被 CasperJS 脚本卡住了:

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

casper.start('http://int.soccerway.com/national/switzerland/super-league/20152016/regular-season/r31601/matches/?ICID=PL_3N_02', function() {
  this.wait(2000, function() {
    fs.write("swiss.html", this.getHTML() );

  });
  this.wait(2000, function() {
    var evObj = document.createEvent('Events');
    evObj.initEvent('click', true, false);
    document.getElementById('page_competition_1_block_competition_matches_6_previous').dispatchEvent(evObj);
  });
  this.wait(2000, function() {
    fs.write("swiss2.html", this.getHTML() );   
  });
});

casper.run();

我想打开代码中的链接,而不是单击上一个并获取页面的 html(我想获取包含每个匹配结果的完整赛季的 html 文档)。

我做错了什么? (我是首发)

谢谢你..

【问题讨论】:

  • 您试图在页面上下文之外使用 DOM,这是不可能的。无论如何,你为什么不使用 CasperJS 的点击功能呢? casper.click(selector)

标签: javascript ajax phantomjs casperjs scraper


【解决方案1】:

脚本几乎是正确的。唯一的错误是与页面交互时(单击“上一个”按钮)。

您无法从脚本内部访问页面元素,您必须在打开的网页上下文中评估(“注入”)该代码。在 CasperJS 中,有 casper.evaluate() 函数可以做到这一点。

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

casper.start('http://int.soccerway.com/national/switzerland/super-league/20152016/regular-season/r31601/matches/?ICID=PL_3N_02', function() {
  this.wait(2000, function() {
    fs.write("swiss.html", this.getHTML() );

  });
  this.wait(2000, function() {

        // Code inside of this function will run 
        // as if it was placed inside the target page.
        casper.evaluate(function(term) {

            var evObj = document.createEvent('Events');
            evObj.initEvent('click', true, false);
            var prev_link = document.getElementById('page_competition_1_block_competition_matches_6_previous');
            prev_link.dispatchEvent(evObj);

        });

  });


  this.wait(2000, function() {
    fs.write("swiss2.html", this.getHTML() );   
  });
});

casper.run();

或者,您可以简单地编写

,而不是使用 casper.evaluate
this.click('#page_competition_1_block_competition_matches_6_previous');

正如 Artjom B. 建议的那样。

【讨论】:

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