javascript - PhantomJS 和 CasperJS 单击链接并获取 html

标签 javascript ajax phantomjs casperjs scraper

我受困于 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 文档)。

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

谢谢你..

最佳答案

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

您无法从脚本内部访问页面元素,您必须在打开的网页上下文中评估(“注入(inject)”)该代码。在 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. 建议的那样。

关于javascript - PhantomJS 和 CasperJS 单击链接并获取 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33808693/

相关文章:

javascript - 将变量从 IPython/Jupyter 内核提取到 javascript

javascript - 动态调整 n 个图像的行大小,所有 5 行高度一致

php - jquery $(event.target).closest ('td' ) 同时多次调用同一函数时得到 'lost'

ajax - 如何让 ajax 回答 slim ?

java - 在java中使用缩放来提高jpeg图像质量

javascript - 无法使用 jQuery 从 PHP 脚本获取结果

未定义 Javascript setInterval 函数

javascript - 未选中复选框时计数器不显示 0

asp.net - 使用 jQuery、Ajax 和 JSON 提交单引号

javascript - Phantomjs 检查响应 header 然后执行某些操作