Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating and executing a Javascript function with Selenium

I am trying to create and execute a JavaScript function with Selenium. I am doing it like this:

js_func = """
     function blah(a, b, c) {
        .
        .
        .
};
"""
self.selenium.execute_script(js_script)
self.selenium.execute_script("blah", 1,2,3)

I don't get any errors from the first one (creating the function), but the second one gives me:

WebDriverException: Message: u'blah is not defined'

Is what I'm doing valid? How I can tell if the function was successfully created? How can I see the errors (assuming there are errors)?

like image 520
Larry Martell Avatar asked Oct 06 '13 19:10

Larry Martell


People also ask

Does Selenium execute JavaScript?

Selenium executes the Javascript commands by taking the help of the execute_script method. The commands to be executed are passed as arguments to the method. Some operations like scrolling down in a page cannot be performed by Selenium methods directly. This is achieved with the help of the Javascript Executor.

Can we execute JavaScript on browser with Selenium?

You an use selenium to do automated testing of web apps or websites, or just automate the web browser. It can automate both the desktop browser and the mobile browser. Selenium webdriver can execute Javascript. After loading a page, you can execute any javascript you want.

Can Selenium scrape JavaScript?

The Selenium browser driver is typically used to scrape data from dynamic websites that use JavaScript (although it can scrape data from static websites too). The use of JavaScript can vary from simple form events to single page apps that download all their content after loading.


1 Answers

It's just how Selenium executes JavaScript:

The script fragment provided will be executed as the body of an anonymous function.

In effect, your code is:

(function() {
    function blah(a, b, c) {
        ...
    }
})();

(function() {
    blah(1, 2, 3);
});

And due to JavaScript's scoping rules, blah doesn't exist outside of that anonymous function. You'll have to make it a global function:

window.blah = function(a, b, c) {
    ...
}

Or execute both scripts in the same function call.

like image 107
Blender Avatar answered Sep 30 '22 19:09

Blender