casperJsで一般的に使用されるAPI



Casperjs Commonly Used Api



インストール

  • phantomjsのインストール
    公式ウェブサイトにアクセスして、圧縮パッケージをダウンロードします。 http://phantomjs.org/download.html
    画像
    それをcドライブに解凍し、名前をphantomjsに変更して、コンピューター環境変数へのパスを追加します。
  • casperjsのインストール
    公式ウェブサイトにアクセスして、圧縮パッケージをダウンロードします。 http://casperjs.org/
    画像
    それをcドライブに解凍し、名前をcasperjsに変更して、コンピューター環境変数へのパスを追加します。

casperjsインスタンスを作成します

casperjsの実行スクリプトは、ステップごとに接続され、startは最初のステップを表し、その後のステップはthenで表され、順番に実行されます。

var casper=require('casper').create({ verbose: true, logLevel: error, viewportSize: { width: 1024, height: 768 }, pageSettings: { loadImages: false // do not load pictures } }) casper.start('www.baidu.com', function(){ this.echo('success!') }) casper.run()

Casperjsファイルを実行します

jsスクリプトのパスの場所にcdします



casperjs test.js

共通API

  • start()、then()、run():Casperのいくつかのステップ
casper.start('www.baidu.com',function(){ //Operation 1 }) casper.then(function(){ //Operation 2 }) casper.then(function(){ //Operation 3 }) casper.run()
  • waitForSelector():WebページのDOMが読み込まれるのを待ちます
casper.start('www.baidu.com',function(){ this.waitForSelector('form[action='/search']') })
  • fill():フォームに入力します
casper.start('https://www.baidu.com/',function(){ this.fill('form#form',{ 'wd':'casperjs' }) })
  • Evaluation():現在のページ環境でjavascriptステートメントを実行します
casper.then(function(){ var rsv_pq = this.evaluate(function(){ return $('input[name=rsv_pq]').val() }) this.echo('rsv_pq: '+rsv_pq) })
  • log():ログを出力します
casper.start('',function(){ this.log('','error') })
  • echo():標準出力に出力
casper.start('www.baidu.com', function(){ this.echo('success!') })
  • Capture()、captureSelector():スクリーンショット
casper.start('www.baidu.com', function() { this.capture('baidu1.png', { top: 100, left: 100, width: 800, height: 400 }) this.captureSelector('baidu2.png','#u1') })
  • scrollTo()、scrollToBottom():ページスクロール
casper.start('www.bilibili.com', function() { this.scrollTo(0, 1200) })

注:ここでは、一般的に使用されるものをいくつかリストしています。これは、APIが非常に少ないことを意味するものではありません。