I'm new to programing in languages more suited to the web, but I have programmed in vba for excel.
What I would like to do is:
- pass a list (in python) to a casper.js script.
- Inside the casperjs script I would like to iterate over the python object (a list of search terms)
- In the casper script I would like to query google for search terms
- Once queried I would like to store the results of these queries in an array, which I concatenate together while iterating over the python object.
- Then once I have searched for all the search-terms and found results I would like to return the RESULTS array to python, so I can further manipulate the data.
QUESTION --> I'm not sure how to write the python function to pass an object to casper.
QUESTION --> I'm also not sure how to write the casper function to pass an javascript object back to python.
Here is my python code.
import os
import subprocess
scriptType = 'casperScript.js'
APP_ROOT = os.path.dirname(os.path.realpath(__file__))
PHANTOM = '\casperjs\bin\casperjs'
SCRIPT = os.path.join(APP_ROOT, test.js)
params = [PHANTOM, SCRIPT]
subprocess.check_output(params)
js CODE
var casper = require('casper').create();
casper.start('http://google.com/', function() {
this.echo(this.getTitle());
});
casper.run();
Could you use JSON to send the data to the script and then decode it when you get it back?
Python:
json = json.dumps(stuff)
//Turn object into string to pass to jsLoad a json file into python:
Deserialize a json string to an object in python
Javascript:
arr = JSON.parse(json)
//Turn a json string to a js arrayjson = JSON.stringify(arr)
//Turn an array to a json string ready to send to pythonYou can use two temporary files, one for input and the other for output of the casperjs script. woverton's answer is ok, but lacks a little detail. It is better to explicitly dump your JSON into a file than trying to parse the console messages from casperjs as they can be interleaved with debug strings and such.
In python:
At the end, the temporary files will be automatically deleted when the objects are garbage collected.
In casperjs:
The casperjs script isn't doing anything useful. It just writes the inputfile to the output file with an added property.