CasperJS API 第一篇

Casperjs 官方API

  • 獲得Casper實例兩種方式

var casper = require(‘casper’).create();

var casper = new require(‘casper’).Casper();

  • create()函數傳參數

var casper = require(‘casper’).create({
clientScripts: [
‘includes/jquery.js’, // These two scripts will be injected in remote
‘includes/underscore.js’ // DOM on every request
],
pageSettings: {
loadImages: false, // The WebPage instance used by Casper will
loadPlugins: false // use these settings
},
logLevel: “info”, // Only “info” level messages will be logged
verbose: true // log messages will be printed out to the console
});

或者在運行時傳遞參數

var casper = require(‘casper’).create();
casper.options.waitTimeout = 1000;

更多參數請查看官方文檔

  • back()

casper.start(‘http://foo.bar/1‘);
casper.thenOpen(‘http://foo.bar/2‘);
casper.thenOpen(‘http://foo.bar/3‘);

casper.back(); //回退頁面函數

casper.run(function() {
console.log(this.getCurrentUrl()); // ‘http://foo.bar/2’ });

  • base64encode()
var base64logo = null;
casper.start('http://www.google.fr/', function() {
    base64logo = this.base64encode('http://www.google.fr/images/srpr/logo3w.png');
});

casper.run(function() {
    this.echo(base64logo).exit();
});

post請求encode

var base64contents = null;
casper.start('http://domain.tld/download.html', function() {
    base64contents = this.base64encode('http://domain.tld/', 'POST', {
        param1: 'foo',
        param2: 'bar'
    });
});

casper.run(function() {
    this.echo(base64contents).exit();
});
  • Selectors
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>My page</title>
</head>
<body>
    <h1 class="page-title">Hello</h1>
    <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
    </ul>
    <footer><p>©2012 myself</p></footer>
</body>
</html>

檢查這裏寫圖片描述是否存在

  • Selectors-CSS3
var casper = require('casper').create();

casper.start('http://domain.tld/page.html', function() {
    if (this.exists('h1.page-title')) {
        this.echo('the heading exists');
    }
});

casper.run();

使用測試框架

casper.test.begin('The heading exists', 1, function suite(test) {
    casper.start('http://domain.tld/page.html', function() {
        test.assertExists('h1.page-title');
    }).run(function() {
        test.done();
    });
});
  • Selectors-Xpath
casper.start('http://domain.tld/page.html', function() {
    this.test.assertExists({
        type: 'xpath',
        path: '//h1[@class="page-title"]'
    }, 'the element exists');
});

建議下面的用法

var x = require('casper').selectXPath;

casper.start('http://domain.tld/page.html', function() {
    this.test.assertExists(x('//h1[@class="page-title"]'), 'the element exists');
});

Warning
The only limitation of XPath use in CasperJS is in the casper.fill() method when you want to fill file fields; PhantomJS natively only allows the use of CSS3 selectors in its uploadFile method, hence this limitation.

  • click()
casper.start('http://google.fr/');

casper.thenEvaluate(function(term) {
    document.querySelector('input[name="q"]').setAttribute('value', term);
    document.querySelector('form[name="f"]').submit();
}, 'CasperJS');

casper.then(function() {
    // Click on 1st result link
    this.click('h3.r a');
});

casper.then(function() {
    // Click on 1st result link
    this.click('h3.r a',10,10);
});

casper.then(function() {
    // Click on 1st result link
    this.click('h3.r a',"50%","50%");
});


casper.then(function() {
    console.log('clicked ok, new location is ' + this.getCurrentUrl());
});

casper.run();

Signature: click(String selector, [Number|String X, Number|String Y]) //selector支持CSS3和XPath

  • clickLabel()

  • capture()

casper.start('http://www.google.fr/', function() {
    this.capture('google.png', {
        top: 100,
        left: 100,
        width: 500,
        height: 400
    });
});

casper.run();
casper.start('http://foo', function() {
    this.capture('foo', undefined, {
        format: 'jpg',
        quality: 75
    });
});
  • captureBase64()
casper.start('http://google.com', function() {
    // selector capture
    console.log(this.captureBase64('png', '#lga'));
    // clipRect capture
    console.log(this.captureBase64('png', {
        top: 0,
        left: 0,
        width: 320,
        height: 200
    }));
    // whole page capture
    console.log(this.captureBase64('png'));
});

casper.run();
  • captureSelector()
casper.start('http://www.weather.com/', function() {
    this.captureSelector('weather.png', '#LookingAhead');
});

casper.run();
  • clear()
casper.start('http://www.google.fr/', function() {
    this.clear(); // javascript execution in this page has been stopped
});

casper.then(function() {
    // ...
});

casper.run();
  • clearCache()
casper.start('http://www.google.fr/', function() {
    this.clearCache(); // cleared the memory cache and replaced page object with newPage().
});

casper.then(function() {
    // ...
});

casper.run();
  • clearMemoryCache()
casper.start('http://www.google.fr/', function() {
    this.clearMemoryCache(); // cleared the memory cache.
});

casper.then(function() {
    // ...
});

casper.run();
  • debugHTML()
var casper = require('casper').create();

casper.start('http://www.migelab.com/', function() {
    this.debugHTML();//輸出html內容代碼到console
});

casper.run();
  • debugPage()
casper.start('http://www.migelab.com/', function() {
    this.debugPage();//輸出文本內容到console
});

casper.run();
  • die()

  • download()

casper.start('http://www.google.fr/', function() {
    var url = 'http://www.google.fr/intl/fr/about/corporate/company/';
    this.download(url, 'google_company.html');
});

casper.run(function() {
    this.echo('Done.').exit();
});
  • each()
var links = [
    'http://google.com/',
    'http://yahoo.com/',
    'http://bing.com/'
];

casper.start().each(links, function(self, link) {
    self.thenOpen(link, function() {
        this.echo(this.getTitle());
    });
});

casper.run();
  • eachThen()
var casper = require('casper').create();
var urls = ['http://google.com/', 'http://yahoo.com/'];

casper.start().eachThen(urls, function(response) {
  this.thenOpen(response.data, function(response) {
    console.log('Opened', response.url);
  });
});

casper.run();
  • echo()
casper.start('http://www.google.fr/', function() {
    this.echo('Page title is: ' + this.evaluate(function() {
        return document.title;
    }), 'INFO'); // Will be printed in green on the console
});

casper.run();

這裏寫圖片描述

  • evaluate()
casper.evaluate(function(username, password) {
    document.querySelector('#username').value = username;
    document.querySelector('#password').value = password;
    document.querySelector('#submit').click();
}, 'sheldon.cooper', 'b4z1ng4');

這裏寫圖片描述

  • evaluateOrDie()
casper.start('http://foo.bar/home', function() {
    this.evaluateOrDie(function() {
        return /logged in/.match(document.title);
    }, 'not authenticated');
});

casper.run();
  • exit()
    Exits PhantomJS with an optional exit status code.
    退出PhantomJS時有一個可選退出狀態碼。
    Note: You can not rely on the fact that your script will be turned off immediately, because this method works asynchronously. It means that your script may continue to be executed after the call of this method. More info here.
    注意:你不能依賴你的腳步會被立即關閉,因爲這個方式異步工作。這意味着exit()被調用時,你的腳步會繼續執行。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章