使用CasperJS,我尝试模拟用户操作,其中包括将xml文件导入到用backbonejs编写的单页Web应用程序中:try.activeeon.com
1) 用户点击“a”html 标签的“导入”
<a id="import-button" href="#" class="pointer"><i class="glyphicon glyphicon-import"></i> Import</a>
2)用户在对话框中选择一个文件,该文件由不带“form”的“input”html标签处理
<input type="file" id="import-file" style="display:none"/>
3) Web 应用加载文件内容
现在,使用 CasperJS,我的脚本会等待,直到使用 waitForResource() 加载页面,然后使用 thenClick 模拟用户单击,然后使用评估()通过调用 setAttribute 设置“input”html 标记的值,并调用 click() 但什么也不做发生了,我尝试使用 fill() ,似乎没有办法填充没有“name”属性的输入,而且捕获的屏幕截图始终为空,似乎网络应用程序没有反应...我也尝试过在 click() 之后在输入元素上调度“change”事件,但没有任何效果。
var casper = require('casper').create({
verbose: true,
logLevel: "debug"
});
var x = require('casper').selectXPath;
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
});
casper.start('http://try.activeeon.com/studio/', function() {
this.echo("Page title: " + this.getTitle());
this.viewport(1366, 768);
});
casper.waitForResource("gears.png", function() {
this.echo('gears.png has been loaded.');
});
casper.thenClick('a[id="import-button"]', function() {
this.wait(2000, function(){
this.evaluate(function(){
var inputElement = document.querySelector('input#import-file');
try {
inputElement.setAttribute('value', 'file.xml');
inputElement.click();
} catch(err) {
console.log("---> oups " + err);
}
});
this.echo('-----------------------------------------');
//this.page.uploadFile('input#import-file','file.xml');
this.fill('input#import-file', {}, true);
this.echo('-----------------------------------------');
this.wait(2000, function() {
this.capture('test-image.jpg', {
top: 0,
left: 0,
width: 1366,
height: 768
});
});
});
});
casper.run();
最佳答案
有一个替代 fill() 方法的方法,称为评估()
http://docs.casperjs.org/en/latest/modules/casper.html#evaluate
关于javascript - 无法使用 CasperJS 在没有表单的情况下填充输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21417388/