1

I need to execute a javascript function on the page, by passing it an array of strings. I want to avoid having to call browser.execute_script number of times.

list_of_strings = ['a','b','c']

#js code runs through all the strings
result = browser.execute_script("function findTexts(textList){//code here}", list_of_strings)
KJW
  • 15,035
  • 47
  • 137
  • 243

1 Answers1

1

Dump python list to JSON and use string formatting:

import json

json_array = json.dumps(list_of_strings)
result = browser.execute_script("function findTexts(%s){//code here}" % json_array)

Here's what js code does it produce:

>>> import json
>>> list_of_strings = ['a','b','c']
>>> json_array = json.dumps(list_of_strings)
>>> "function findTexts(%s){//code here}" % json_array
'function findTexts(["a", "b", "c"]){//code here}'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • in the javascript code, how would I iterate through the list? what if the number of items in the list is unpredictable? – KJW Jun 19 '14 at 07:30
  • @KJW just use a basic javascript loop, see http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript. – alecxe Jun 19 '14 at 18:32
  • I ended up doing this `browser.evaluate_script("findTexts(%s);function findTexts(list){//do something with list array}");` turns out `evaluate_script` returns the results. – KJW Jun 19 '14 at 18:45