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 C6H14 2-Methylpentane</option>
<option value="1 24"> 75-07-0 C2H4O Acetaldehyde</option>
<option value="6 2">106-93-4 C2H4Br2 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:
Navigate to http://www.ddbst.com/unifacga.html
Select option no. 4 (DDB search)
Enter e.g. 174 as the ddb number and submit.
You should now see a "complist" with a single option for water.
How can I return the option value?
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
});