HRVHackers
HRVHackers

Reputation: 2873

Javascript: Modify code to add elements to an array/list

Hey Guys, Javascript newbie here. I'm trying to modify some existing to code to instead of returning the count of elements, to actually add each of the specified elements to an array/list

here is the original code from Selenium CSS counter

private int getCSSCount(String aCSSLocator){
String jsScript = "var cssMatches = eval_css(\"%s\", window.document);cssMatches.length;";
return Integer.parseInt(selenium.getEval(String.format(jsScript, aCSSLocator)));

}

I then have to convert the code to python, which I am far more familiar with

        def count_css_matches(self, css_locator):
        java_script_code = '''
            var cssMatches = eval_css("%s", window.document);
            cssMatches.length;''' % css_locator
        return int(self.selenium.get_eval(java_script_code))

But changing the original code to return the array instead of an integer is where I get stuck.

Thanks for the help and the below is the error I get when I tried to run it in Python.

Traceback (most recent call last): "D:\Temp\1TestingApps\Selenium\SeleniumRC\selenium-python-client-driver-1.0.1\selenium.py", line 1218, in get_eval return self.get_string("getEval", [script,]) File "D:\Temp\1TestingApps\Selenium\SeleniumRC\selenium-python-client-driver-1.0.1\selenium.py", line 219, in get_string result = self.do_command(verb, args) File "D:\Temp\1TestingApps\Selenium\SeleniumRC\selenium-python-client-driver-1.0.1\selenium.py", line 215, in do_command raise Exception, data Exception: ERROR: Threw an exception: missing ) after argument list

Upvotes: 0

Views: 740

Answers (2)

AutomatedTester
AutomatedTester

Reputation: 22438

If you update your python bindings you will have it. pip install -U selenium

Upvotes: 0

Gonzalo Larralde
Gonzalo Larralde

Reputation: 3541

I'm not sure how eval_css works, but if returns an array of strings into cssMatches, as you can get an string, and not a list, using get_eval, then you should JSONify the list in the JS scope, getting it as an string into python, and using simplejson, converting it to an python's native list.

Something like this, I guess:

import json

def count_css_matches(self, css_locator):
    java_script_code = '''
        var cssMatches = eval_css("%s", window.document);
        JSON.stringify(cssMatches.length);''' % css_locator

    return json.loads(self.selenium.get_eval(java_script_code)))

I don't know if you need a return, document.write, or something like that in the js code to get the string. Please add a comment if it's needed, and I'll add it to the code :-)

Good luck!

Upvotes: 1

Related Questions