How to click on selectbox options using PhantomJS

左心房为你撑大大i 提交于 2019-11-30 21:21:14
Artjom B.

You can't click (trigger a click event) on options of a select box. You need to change the selected option and then trigger a change event. For example:

var sel = document.querySelector('select.se1');
sel.selectedIndex = 2;
var event = new UIEvent("change", {
    "view": window,
    "bubbles": true,
    "cancelable": true
});
sel.dispatchEvent(event);

You can package that in a function

function selectOption(selector, optionIndex) {
    page.evaluate(function(selector, optionIndex){
        var sel = document.querySelector(selector);
        sel.selectedIndex = optionIndex;
        var event = new UIEvent("change", {
            "view": window,
            "bubbles": true,
            "cancelable": true
        });
        sel.dispatchEvent(event);
    }, selector, optionIndex);
}

Then you can call it one after the other

selectOption("select.se1", 2);
selectOption("select.se2", 0);
selectOption("select.se3", 0);
...

You get the idea. In case the onChange event of the select box needs remote data for example through AJAX, then you will need to wait between the calls. Either use a static wait time (see following example) or use waitFor().

setTimeout(function(){
    selectOption("select.se1", 2);
}, 1000);
setTimeout(function(){
    selectOption("select.se2", 0);
}, 2000);
setTimeout(function(){
    selectOption("select.se3", 0);
}, 3000);
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!