简体   繁体   English

如何用CasperJS填充未嵌入表单的选择元素?

[英]How to fill a select element which is not embedded in a form with CasperJS?

My html code is: 我的html代码是:

<div class="setting-control">
<select class="on-off" id="custom-cache-pref">
  <option value="">Default</option>
  <option value="byc">Bypass cache</option>
  <option value="basic">Basic caching</option>
  <option value="iqs">Ignore query string</option>
  <option value="agg">Aggressive caching</option>
  <option value="all">Cache everything</option>
</select>
</div>

Usually with casperjs I would use 通常我会用casperjs

this.fillSelectors('form[name="formName"]', { 
    'select[id="custom-cache-pref"]': 'byc'                     
}, false);

to select option "byc" but this time the "select" element is not embedded in a form! 选择选项“ byc”,但是这次“ select”元素未嵌入表单中!

How can I choose its value in this case? 在这种情况下,如何选择其值?

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. 这将更改选定的索引,这可能不会触发select onChange事件。

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 选择1

Judging by the code of __utils__.fill() and casper.fillForm() , the selector of the form doesn't necessarily have to be a form. __utils__.fill()casper.fillForm()的代码来看,表单的选择器不一定是表单。 It may be a div: 它可能是一个div:

this.fillSelectors('div.setting-control', { 
    'select[id="custom-cache-pref"]': 'byc'                     
}, false);

Alternative 2 选择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() : 如果仍然page.sendEvent() ,您可能需要专注于页面上下文中的select元素,并使用PhantomJS的page.sendEvent()发送上下键事件以更改值:

this.evaluate(function(){
    document.querySelector('select[id="custom-cache-pref"]').focus();
});
this.page.sendEvent('keypress', this.page.event.key.Down);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM