如何:使用CasperJS打印选择选项值?

时间:2016-11-14 10:10:18

标签: javascript list phantomjs casperjs options

我正在尝试打印" 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);
    }
});

但是我收到以下错误:

  • 错误&GT; ReferenceError:无法找到变量:options,ERROR
  • 文件&gt; phantomjs://code/gruppen3.js,警告
  • 线&GT; 113,警告
  • 功能&GT; ,警告

由for循环中的 options.length 生成:/

我尝试了其他几种方式(例如How to select an option with CasperJS)来返回选项列表,但到目前为止还没有任何工作。

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

  1. 导航至http://www.ddbst.com/unifacga.html
  2. 选择选项号。 4(DDB搜索)
  3. 输入例如174作为ddb号并提交。
  4. 您现在应该看到&#34; complist&#34;只有一个水选项。
  5. 如何返回选项值?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

我已经对它进行了测试,它确实有效!

t

您可以使用以下方式运行它:
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();

答案 1 :(得分:1)

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    
});