【发布时间】:2014-11-03 17:50:47
【问题描述】:
我正在尝试使用 CasperJS 来模拟用户操作,该操作包括将 xml 文件导入到使用主干js 编写的单页 Web 应用程序中:try.activeeon.com
1) 用户点击“a”html标签的“Import”
<a id="import-button" href="#" class="pointer"><i class="glyphicon glyphicon-import"></i> Import</a>
2) 用户在对话框中选择一个文件,该文件由没有“表单”的“输入”html 标记处理
<input type="file" id="import-file" style="display:none"/>
3) 网络应用加载文件的内容
现在使用 CasperJS,我的脚本一直等到使用 waitForResource() 加载页面,然后使用 thenClick 模拟用户点击,然后使用 evaluate() 通过调用 setAttribute 并调用 click() 设置“输入”html 标记的值,但没有发生了,我尝试使用fill(),似乎没有办法填充没有“名称”属性的输入,而且捕获的屏幕截图总是空的,似乎网络应用程序没有反应......我也试过在 click() 之后在 input 元素上调度一个“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();
【问题讨论】:
-
您是否尝试过使用 casper.fill 功能? docs.casperjs.org/en/latest/modules/casper.html#fill
-
是的,我试过了,它没有效果,并且从文档中:fill() 函数采用“name”属性引用的字段,而我要填充的输入标签没有“name”属性。
-
我明白了。我认为您的问题更多是关于如何填写文件输入女巫 casper。
-
你不能用JS填充文件输入,但是phantomjs有一个函数uploadFile。尝试时发生了什么?
-
我尝试添加 casper.then(function(){this.page.uploadFile('input#import-file','file.xml');});在 waitForResource 调用之后,即使文件名不正确,日志中也没有发生任何事情。
标签: javascript html casperjs