CasperJS API 第二篇

  • exists()
casper.start('http://foo.bar/home', function() {
    if (this.exists('#my_super_id')) {
        this.echo('found #my_super_id', 'INFO');
    } else {
        this.echo('#my_super_id not found', 'ERROR');
    }
});

casper.run();
  • fetchText()
casper.start('http://google.com/search?q=foo', function() {
    this.echo(this.fetchText('h3'));
}).run();
  • forward()
casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back();    // http://foo.bar/2
casper.back();    // http://foo.bar/1
casper.forward(); // http://foo.bar/2
casper.run();
  • log()
casper.start('http://www.google.fr/', function() {
    this.log("I'm logging an error", "error");
});

casper.run();

http://some.tld/contact.form, fill(), fillSelectors(), fillLabels(), fillXPath().

<form action="/contact" id="contact-form" enctype="multipart/form-data">
    <input type="text" name="subject"/>
    <textearea name="content"></textearea>
    <input type="radio" name="civility" value="Mr"/> Mr
    <input type="radio" name="civility" value="Mrs"/> Mrs
    <input type="text" name="name"/>
    <input type="email" name="email"/>
    <input type="file" name="attachment"/>
    <input type="checkbox" name="cc"/> Receive a copy
    <input type="submit"/>
</form>
  • fill()
casper.start('http://some.tld/contact.form', function() {
    this.fill('form#contact-form', {
        'subject':    'I am watching you',
        'content':    'So be careful.',
        'civility':   'Mr',
        'name':       'Chuck Norris',
        'email':      '[email protected]',
        'cc':         true,
        'attachment': '/Users/chuck/roundhousekick.doc'
    }, true);
});

casper.then(function() {
    this.evaluateOrDie(function() {
        return /message sent/.test(document.body.innerText);
    }, 'sending message failed');
});

casper.run(function() {
    this.echo('message sent').exit();
});

For multiple selects, supply an array of values to match against:

<form action="/contact" id="contact-form" enctype="multipart/form-data">
    <select multiple name="category">
    <option value=​"0">Friends​</option><option value=​"1">​Family​</option><option value=​"2">​Acquitances​</option><option value=​"3">​Colleagues</option></select>
</form>
casper.then(function() {
   this.fill('form#contact-form', {
       'categories': ['0', '1'] // Friends and Family
   });
});
  • fillSelectors()
casper.start('http://some.tld/contact.form', function() {
    this.fillSelectors('form#contact-form', {
        'input[name="subject"]':    'I am watching you',
        'input[name="content"]':    'So be careful.',
        'input[name="civility"]':   'Mr',
        'input[name="name"]':       'Chuck Norris',
        'input[name="email"]':      '[email protected]',
        'input[name="cc"]':         true,
        'input[name="attachment"]': '/Users/chuck/roundhousekick.doc'
    }, true);
});
  • fillLabels()
casper.start('http://some.tld/contact.form', function() {
    this.fillLabels('form#contact-form', {
        Email:         '[email protected]',
        Password:      'chuck',
        Content:       'Am watching thou',
        Check:         true,
        No:            true,
        Topic:         'bar',
        Multitopic:    ['bar', 'car'],
        File:          fpath,
        "1":           true,
        "3":           true,
        Strange:       "very"
    }, true);
});
  • fillXPath()
casper.start('http://some.tld/contact.form', function() {
    this.fillXPath('form#contact-form', {
        '//input[@name="subject"]':    'I am watching you',
        '//input[@name="content"]':    'So be careful.',
        '//input[@name="civility"]':   'Mr',
        '//input[@name="name"]':       'Chuck Norris',
        '//input[@name="email"]':      '[email protected]',
        '//input[@name="cc"]':         true,
    }, true);
});
  • getCurrentUrl()
casper.start('http://www.google.fr/', function() {
    this.echo(this.getCurrentUrl()); // "http://www.google.fr/"
});

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

casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementAttribute('div[title="Google"]', 'title')); // "Google"
});

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

casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementsAttribute('div[title="Google"]', 'title')); // "['Google']"
});

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

casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementBounds('div[title="Google"]'));
});

casper.run();
  • getElementsBounds()

  • getElementInfo()

casper.start('http://google.fr/', function() {
    require('utils').dump(this.getElementInfo('#hplogo'));
});
  • getElementsInfo()
casper.start('http://google.fr/', function() {
    require('utils').dump(this.getElementsInfo('#hplogo'));
});
  • getFormValues()
casper.start('http://www.google.fr/', function() {
    this.fill('form', {q: 'plop'}, false);
    this.echo(this.getFormValues('form').q); // 'plop'
});

casper.run();
  • getGlobal()
casper.start('http://www.google.fr/', function() {
    this.echo(this.getGlobal('innerWidth')); // 1024
});

casper.run();
  • getHTML()
casper.start('http://www.google.fr/', function() {
    this.echo(this.getHTML());
});

casper.run();
casper.start('http://www.site.tld/', function() {
    this.echo(this.getHTML('h1#foobar')); // => 'Plop'
});
casper.start('http://www.site.tld/', function() {
    this.echo(this.getHTML('h1#foobar', true)); // => '<h1 id="foobar">Plop</h1>'
});
  • getPageContent()
var casper = require('casper').create();

casper.start().then(function() {
    this.open('http://search.twitter.com/search.json?q=casperjs', {
        method: 'get',
        headers: {
            'Accept': 'application/json'
        }
    });
});

casper.run(function() {
    require('utils').dump(JSON.parse(this.getPageContent()));
    this.exit();
});
  • getTitle()
casper.start('http://www.google.fr/', function() {
    this.echo(this.getTitle()); // "Google"
});

casper.run();
  • mouseEvent()

The list of supported events depends on the version of the engine in
use. Older engines only provide partial support. For best support use
recent builds of PhantomJS or SlimerJS.”:

casper.start('http://www.google.fr/', function() {
    this.mouseEvent('click', 'h2 a', "20%", "50%");
});

casper.run();
  • newPage()
casper.start('http://google.com', function() {
    // ...
});

casper.then(function() {
    casper.page = casper.newPage(); //Creates a new WebPage instance
    casper.open('http://yahoo.com').then( function() {
        // ....
    });
});

casper.run();
  • open()

Example for a standard GET request:

casper.start();

casper.open('http://www.google.com/').then(function() {
    this.echo('GOT it.');
});

casper.run();

Example for a POST request:

casper.start();

casper.open('http://some.testserver.com/post.php', {
    method: 'post',
    headers: {
       'Content-Type': 'application/json; charset=utf-8'
    },
    encoding: 'utf8', // not enforced by default
    data:   {
        'title': 'Plop',
        'body':  'Wow.',
        'standard_param': 'foo',
        'nested_param[]': [   // please note the use of square brackets!
            'Something',
            'Something else'
        ]
    }
});

casper.then(function() {
    this.echo('POSTED it.');
});

casper.run();
  • reload()
casper.start('http://google.com', function() {
    this.echo("loaded");
    this.reload(function() {
        this.echo("loaded again");
    });
});

casper.run();
  • repeat()
casper.start().repeat(3, function() {
    this.echo("Badger");
});

casper.run();
  • resourceExists()
casper.start('http://www.google.com/', function() {
    if (this.resourceExists('logo3w.png')) {
        this.echo('Google logo loaded');
    } else {
        this.echo('Google logo not loaded', 'ERROR');
    }
});

casper.run();
  • run()

Runs the whole suite of steps and optionally executes a callback when they’ve all been done. Obviously, calling this method is mandatory in order to run the Casper navigation suite.
運行一整套步驟並在完成時有選擇地執行一個回調。很明顯,調用此方法是強制性的,爲了運行Casper的導航套件。

Casper.run() also accepts an onComplete callback, which you can consider as a custom final step to perform when all the other steps have been executed. Just don’t forget to exit() Casper if you define one!:
Casper.run() 接受一個完成時的回調,你可以把這看做一個自定義最後執行的步驟,當所有其他的步驟已經被執行。但是不要忘了調用exit()退出Casper。

casper.run(function() {
    this.echo('So the whole suite ended.');
    this.exit(); // <--- don't forget me!
});
  • scrollTo()
casper.start('http://foo.bar/home', function() {
    this.scrollTo(500, 300);
});
  • scrollToBottom()
casper.start('http://foo.bar/home', function() {
    this.scrollToBottom();
});
  • sendKeys()
casper.then(function() {
    this.sendKeys('form.contact input#name', 'Duke');
    this.sendKeys('form.contact textarea#message', "Damn, I'm looking good.");
    this.click('form.contact input[type="submit"]');
});
  • setHttpAuth()
casper.start();

casper.setHttpAuth('sheldon.cooper', 'b4z1ng4');

casper.thenOpen('http://password-protected.domain.tld/', function() {
    this.echo("I'm in. Bazinga.");
})
casper.run();
var url = 'http://sheldon.cooper:[email protected]/';

casper.start(url, function() {
    this.echo("I'm in. Bazinga.");
})

casper.run();
  • setMaxListeners()
casper.setMaxListeners(12);
  • start()
casper.start('http://google.fr/', function() {
    this.echo("I'm loaded.");
});

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

casper.then(function() {
    this.echo("I'm loaded.");
});

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

casper.then(function() {
    casper.echo("I'm loaded.");
});

casper.run();
  • status()
casper.start('http://google.fr/', function() {
    this.echo(this.status(true));
});

casper.run();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章