大家好我想知道如何使用casperjs获取输入值
这是我的html元素
<input type="hidden" name="key" value="newkey">
这就是我的尝试:
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);
在这种情况下,请返回null
我也尝试过:
activationKey = __utils__.getFieldValue('key');
但请回复此错误:
FAIL ReferenceError: Can't find variable: __utils__
答案 0 :(得分:11)
尝试使用:
this.getElementAttribute('input[type="hidden"][name="key"]', 'value');
答案 1 :(得分:5)
如果动态设置了值,那么this.getElementAttribute
将无效,__utils__.getFieldValue
也无效。从1.1.3开始,唯一的方法是调用底层文档对象的querySelector。
var value = this.evaluate(function() {
return document.querySelector('[name="key"]').value
})
有点冗长,但至少它有效。
此外,关于无法找到__utils__的原因,请使用以下内容导入它:
var __utils__ = require('clientutils').create()
在OP的例子中,__ utils__位于evaluate()函数中。它不应该是,因为__utils__是一个casper的东西,而不是DOM / javascript的东西。