Domanda

Hi allm I would like to know how to get an input value with casperjs

This is my html element

<input type="hidden" name="key" value="newkey">

This is what I have tried:

    view            = 'users/registered';

    casper.test.begin("Activating account", 5, function register(test){
        casper.start(webroot + view, function(){

        }).then(function(){
            this.echo("Retrieving data from hidden input key", "COMMENT");

            activationKey = this.evaluate(function() {
                return __utils__.getFieldValue('key');
            });

        }).then(function(){
            this.echo("Activating account with the key \"" + activationKey + "\"", "COMMENT");
            window.location = webroot + activationKey;
        });

        casper.run(function() {
            this.echo('Account activated successfully', 'SUCCESS').exit();
            test.done();
        });
    });

casper.viewport(page.width, page.height);

In this case return null

I have also tried:

activationKey = __utils__.getFieldValue('key');

but return me this error:

FAIL ReferenceError: Can't find variable: __utils__
È stato utile?

Soluzione

Try using this :

this.getElementAttribute('input[type="hidden"][name="key"]', 'value');

Altri suggerimenti

If the value is set dynamically, then this.getElementAttribute won't work, nor will __utils__.getFieldValue. The only way, as of 1.1.3, is to call the underlying document object's querySelector.

  var value = this.evaluate(function() {
    return document.querySelector('[name="key"]').value
  })

A bit verbose, but at least it works.

Also, regarding why __utils__ couldn't be found, use the following to import it:

var __utils__ = require('clientutils').create()

In the OP's example, __utils__ is in the evaluate() function. It shouldn't be, as __utils__ is a casper thing, not a DOM/javascript thing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top