2016年8月10日 星期三

利用 CasperJS 自動換領 Packt 免費電子書

繼續前天的研究。既然 SimpleTest 不行,那就嘗試其他工具,因此昨天安裝了 CasperJS

CasperJS 跟 SimpleTest 不同的是,它需要利用 Firefox 來進行協作,一些特別的處理也能完成。甚至把畫面輸出成 PNG 圖檔。經過一番嘗試,最終成功實現了目標,透過執行以下代碼「node_modules/casperjs/bin/casperjs packt.js」便能順利換領 Packt 免費電子書!
//----------------------------------------------------------------------------------------
//  Packt Free eBook Downloader
//----------------------------------------------------------------------------------------
//  Platform: macOS + PhantomJS + CasperJS + Javascript
//  Written by Pacess
//  Copyright 2016 Pacess Studio.  All rights reserved.
//----------------------------------------------------------------------------------------

var casper = require("casper").create();

//  Load free ebook page
var host = "https://www.packtpub.com";
var url = host+"/packt/offers/free-learning";
casper.start(url);

//  Once page loaded, login first
casper.then(function()  {
   this.echo("Logging in...");
   this.fillSelectors("#packt-user-login-form-respo", {
      "#email": "sita@chan.com",
      "#password": "Sita0310"
   }, true);
});

//  Once login, then extract claim URL
casper.then(function()  {
   this.echo("Extracting claim URL...");

   url = "";
   var html = this.getHTML();
   var index = html.search("/freelearning-claim/");
   this.echo("Index: "+index);
   if (index >= 0)  {

      //  Claim pattern found
      var link = html.substring(index, index+40);
      index = link.search("\"");
      if (index >= 0)  {

         //  Construct complete claim URL
         url = host+link.substring(0, index);
         this.echo("Claim URL: "+url);
         casper.thenOpen(url, function()  {
            this.echo("URL: "+this.getCurrentUrl());
         });
      }
   }
});

//  If there is error, log it out
casper.on("error", function(msg, backtrace)  {
   this.echo("### "+msg);
   throw new ErrorFunc("fatal", "error", "filename", backtrace, msg);
});

//  Run above script now!
casper.run();

沒有留言: