casperjs中fill()方法的使用

Winterto1990發表於2015-10-16


Signature: fill(String selector, Object values[, Boolean submit])

Fills the fields of a form with given values and optionally submits it. Fields are referenced by their name attribute.
Changed in version 1.1: To use CSS3 or XPath selectors instead, check the fillSelectors() and fillXPath() methods.
Example with this sample html form:

<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>

A script to fill and submit this form:

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': 'chuck@norris.com',
'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();
});


The fill() method supports single selects in the same way as text input. 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>

A script to select multiple options for category in this form:

casper.then(function() {
this.fill('form#contact-form', {
'categories': ['0', '1'] // Friends and Family
});
});

Warning:
1. The fill() method currently can’t fill file fields using XPath selectors; PhantomJS natively only allows
the use of CSS3 selectors in its uploadFile() method, hence this limitation.
2. Please Don’t use CasperJS nor PhantomJS to send spam, or I’ll be calling the Chuck. More seriously, please
just don’t.





相關文章