javascriptlistphantomjscasperjs

How to: Print Select Option Values?


I am trying to print the values of each option in the "complist", which looks something like this:

<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>

I tried:

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

But I get the following error:

Which results from options.length in the for-loop:/

I tried a couple of other ways (e.g. How to select an option with CasperJS) to return the list of options, but nothing has worked so far.

To see exactly what I am talking about you can:

  1. Navigate to http://www.ddbst.com/unifacga.html

  2. Select option no. 4 (DDB search)

  3. Enter e.g. 174 as the ddb number and submit.

  4. You should now see a "complist" with a single option for water.

How can I return the option value?


Solution

  • casper.evaluate executes javascript inside of a sandbox. You have to specifically return data from that function because variables created there will not exist in the main script. The correct implemenation:

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