Python selenium – execute javascript code

Selenium code in python can execute custom Javascript and also return values from webdriver (PhantomJS, Firefox, Chrome. etc.) context. Here is sample code which counts total number of links in the page. Note that you must have PhantomJS and python selenium bindings installed for this tutorial. We’ll use Mac for this tutorial but it should work on Linux also. For running it in non GUI mode, we’ll use PhantomJS as driver.

from selenium import webdriver

driver = webdriver.PhantomJS("/usr/local/bin/phantomjs")
var global_total_links=0;
jQuery("a").each(function() {
return global_total_links;
retval = driver.execute_script(jscode);
print retval

Run above code on command line

$ python

Few points to node

  1. We are using python heredoc syntax (code within ''' and '''). That way it is easy to write readable js code.
  2. The javascript code can conflict with page Javascript and can possibly cause errors. You may want to make sure you don’t create conflicting global variables.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments