如何:打印选择选项值

How to: Print Select Option Values?

本文关键字:选项 选择 打印 如何      更新时间:2023-09-26

我正在尝试打印"complist"中每个选项的值,它看起来像这样:

<select name="complist">
    <option selected="" value="111 1">107-83-5&nbsp;&nbsp;C6H14&nbsp;&nbsp;2-Methylpentane</option>
    <option value="1 24">&nbsp;75-07-0&nbsp;&nbsp;C2H4O&nbsp;&nbsp;&nbsp;&nbsp;Acetaldehyde</option>
    <option value="6 2">106-93-4&nbsp;&nbsp;C2H4Br2&nbsp;&nbsp;Ethylene bromide</option>
</select>

我试着:

casper.then(function(){
    this.evaluate(function(){
        //var options = document.querySelectorAll('select[name="complist"]'); 
        var options = document.querySelector('select[name="complist"]');
    })
    for (var i=0; i< options.length; i++){
        console.log(">>> " + options[i].textContent);
    }
});

但是我得到以下错误:

  • Error>参考错误:Can't find variable: options, ERROR
  • File>phantomjs://代码/gruppen3.js,警告
  • Line>113年,警告
  • Function>,警告

选项产生。for循环的长度:/

我尝试了一些其他的方法(例如如何使用CasperJS选择一个选项)来返回选项列表,但是到目前为止没有任何工作。

要确切地了解我在说什么,你可以:

  1. 导航到http://www.ddbst.com/unifacga.html

  2. 选择选项no。4 (DDB搜索)

  3. 输入例如174作为ddb号并提交。

  4. 现在您应该可以看到一个"只有一个水选项。

如何返回选项值?

我已经测试过了,它可以工作!

var casper = require('casper').create({verbose: true,logLevel: "debug"});
casper.start('http://www.ddbst.com/unifacga.html',function(){
this.withFrame('ircframe',function(){
this.click('input[id="ID4"]');
this.wait(0,function(){
this.fillSelectors('form[name="opeform"]', {'input[name="ddbnumber"]': '155'},false);
});
this.wait(0,function(){this.click('input[name="search_ddbnum"]');});
this.wait(0,function(){
var i,o=this.fetchText('select[name="complist"]');
console.log("The value is: "+o)
});
});
});
casper.then(function(){this.capture('test.png');});
casper.run();

你可以用:
./casperjs --web-security=no test.js >>/dev/stdout

casper.evaluate在沙盒内执行javascript。您必须专门从该函数返回数据,因为在那里创建的变量将不存在于主脚本中。正确的实现:

/// MAIN SCRIPT CONTEXT
casper.then(function(){
    // Value which is returned from sandbox must be saved in some local variable
    var localOptions = this.evaluate(function(){
        // SANDBOX CONTEXT -------------------------------
        // Dont return objects. Return arrays, strings, numbers
        var options = [];
        options = [].map.call(document.querySelectorAll('select[name="complist"] option'), function(option){
            return option.innerText;
        });
        // You have to return scraped data back to the outer script
        return options;
        // END OF SANDBOX CONTEXT -----------------------
    });
    console.log(">>> " + localOptions);
    // just "options" array does not exist here    
});