这是我的问题:我在一个特定的情况下尝试设置选择下拉列表的选项。我通常使用this.mouse.up() + this.mouse.down()
,但在这种情况下我不能,因为这种行为在带有 webkit 的网站上不起作用(您可以将两者与 google chrome 和 Firefox 进行比较)。
这里是网址:在我的示例中,我想将字段“ANNEE”设置为 2008 年
我的代码:(我的函数更改了 HTML 并启动了 change() 事件)
//custom function
casper.fillSelect = function(selectSelector, optionText){
this.evaluate(function(sel,setByText) {
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents")
,x = document.querySelectorAll(sel + ' > option')
,l = x.length
;
evt.initEvent("change", false, true);
for (i=0; i<l; i++){
if(x[i].textContent.indexOf(setByText) !== -1){
console.log(x[i]);
console.log(x[i].getAttribute('value'));
x[i].setAttribute('selected', true);
x[i].parentNode.dispatchEvent(evt);
}
}
}
else {console.log("error with fillSelect");}
},selectSelector, optionText);
};
//event
casper.test.on('fail', function(failure) {
casper.capture('fail.png');
});
/*************************************** Tests *****************************************************/
casper.test.begin('\n********* Compare : ***********', function (test) {
"use strict";
casper.start()
.thenOpen("http://www.linternaute.com/voyage/climat/paris/ville-75056",function(){
casper.fillSelect('fieldset.fcNeutre > div.odSelect:nth-of-type(2) > select', '2008');
})
.waitForUrl(/2008/, function(){
this.capture('fail2.png');
this.test.assertSelectorHasText("h2", "maximales");
this.test.assertSelectorHasText("h2", "minimales");
this.test.assertSelectorHasText("h2", "Paris");
this.test.assertSelectorHasText("h2", "Le soleil");
this.test.assertSelectorHasText("h2", "La pluie");
this.test.assertExists("tspan");
this.test.assertExists("div.marB20");
this.test.assertNotEquals(this.fetchText("div.marB20 > table > thead > tr > th"), "", "Table first data not empty");
})
.run(function() {
this.test.comment('--- Done ---\n');
test.done();
});
});
和我的 casper 自定义函数等价,你可以在浏览器中执行它:
var fillSelect = function(sel,setByText) {
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents")
,x = document.querySelectorAll(sel + ' > option')
,l = x.length
;
evt.initEvent("change", false, true);
for (i=0; i<l; i++){
if(x[i].textContent.indexOf(setByText) !== -1){
//console.log(x[i]);
//console.log(x[i].getAttribute('value'));
x[i].setAttribute('selected', true);
x[i].parentNode.dispatchEvent(evt);
}
}
}
else {console.log("error with fillSelect");}
};
fillSelect('fieldset.fcNeutre > div.odSelect:nth-of-type(2) > select', '2008');
所以它适用于 FF、谷歌浏览器、slimerJS,但不适用于 PhantomJS ...请帮助,如果你有另一个想法,只需在这个 'ANNEE' 字段中选择一个选项,使用 casper+phantom,我接受!
会不会是浏览器兼容性的问题?
这很奇怪,因为在同一个网站中,有时它与其他“选择”一起使用,与这个相同......