Adapted from my answer here, you can create your own function that selects an option by value. This changes the selected index which might not trigger the select onChange event.
casper.selectOptionByValue = function(selector, valueToMatch){
this.evaluate(function(selector, valueToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.value.indexOf(valueToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
// dispatch change event in case there is some kind of validation
var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
evt.initUIEvent("change", true, true);
select.dispatchEvent(evt);
}, selector, valueToMatch);
};
casper.start(url, function() {
this.selectOptionByValue('select#custom-cache-pref', "byc");
}).run();
Alternative 1
Judging by the code of __utils__.fill()
and casper.fillForm()
, the selector of the form doesn't necessarily have to be a form. It may be a div:
this.fillSelectors('div.setting-control', {
'select[id="custom-cache-pref"]': 'byc'
}, false);
Alternative 2
If this still doesn't work, you might need to resort on focusing on the select element in the page context and sending up and down key events to change the value using PhantomJS' page.sendEvent()
:
this.evaluate(function(){
document.querySelector('select[id="custom-cache-pref"]').focus();
});
this.page.sendEvent('keypress', this.page.event.key.Down);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…