7

I've been using XPath with Selenium quite happily and even using getEval with a but of Javascript, but a colleague said wouldn't it be great to be able to use JQuery selectors in Selenium.

I've googled it, but can't find any articles that seem to work for me. Could anyone provide a comprehensive guide on how to use JQuery syntax to extract doc elements and their respective values out of selenium.

I'm using C# to write my selenium tests, so if any examples could be from a C# perspective that'd be great.

Thanks

raksja
  • 3,969
  • 5
  • 38
  • 44
danswain
  • 4,171
  • 5
  • 37
  • 43

3 Answers3

9

Karl Swedberg wrote an excellent blog entry about it which can be found at http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet

We adapted this and basically in the Selenium Server jar file we modified RemoteRunner.html to include the jquery JavaScript (obtained from http://code.jquery.com/jquery-latest.min.js):

        <script language="JavaScript" type="text/javascript" src="jquery.min.js"></script>
        <script language="JavaScript" type="text/javascript">
            function openDomViewer() {
                var autFrame = document.getElementById('selenium_myiframe');
                var autFrameDocument = new SeleniumFrame(autFrame).getDocument();
                this.rootDocument = autFrameDocument;
                var domViewer = window.open(getDocumentBase(document) + 'domviewer/domviewer.html');
                return false;
            }
        </script>

Then to enable this for use in Selenium we add the location strategy:

mySelenium.addLocationStrategy("jquery",
            "var loc = locator; " +
            "var attr = null; " +
            "var isattr = false; " +
            "var inx = locator.lastIndexOf('@'); " +

            "if (inx != -1){ " +
            "   loc = locator.substring(0, inx); " +
            "   attr = locator.substring(inx + 1); " +
            "   isattr = true; " +
            "} " +

            "var found = jQuery(inDocument).find(loc); " +
            "if (found.length >= 1) { " +
            "   if (isattr) { " +
            "       return found[0].getAttribute(attr); " +
            "   } else { " +
            "       return found[0]; " +
            "   } " +
            "} else { " +
            "   return null; " +
            "}"
        );

Note the above addition of locator strategy is in Java but its just a string so should be easily replicated in C#. JQuery does make things a lot faster, especially in Internet Explorer!

To modify the jar you can use the java command line tool to update the downloaded selenium server jar. Make a folder at the same level as the jar called "core" and put the modified RemoteRunner.html and jquery.min.js files there. Then run something like:

jar -uf selenium-server-standalone-2.0b3-APT.jar core\RemoteRunner.html
jar -uf selenium-server-standalone-2.0b3-APT.jar core\jquery.min.js

If jar isn't in your path you can use the full path, for example on windows you could execute it with something like:

"C:\Program Files\Java\jdk1.6.0_22\bin\jar.exe" <arguments>
Aaron Silverman
  • 22,070
  • 21
  • 83
  • 103
  • i found this very intersting! but the main question is: how can we use this jquery-extension, eg. type in a textarea selected by jquery? –  Jun 02 '10 at 10:51
  • 2
    @Andreas you just use the jquery= to start your locator expression and then use jquery! Example locator expression (intentionally not simplest example): "jquery=table#myParentTableID > input.input-class" – Aaron Silverman Jun 07 '10 at 15:58
  • 2
    Hey, I battled with this for a while before realising I had to put the script tags mentioned into RemoteRunner.html rather than TestRunner. – Rodreegez Jul 15 '10 at 15:41
  • @Rodreegez -- sorry about mixing up the file, you are absolutely right. I will update my answer. – Aaron Silverman Apr 21 '11 at 21:29
  • @Zugwalt: this is just fantastic. But... Is there a way to add a custom jQuery locator builder to Selenium IDE in FF, so that we do not have to write the jQuery selectors manually but rather get them from a recorded test case? – Pierpaolo Nov 13 '12 at 11:12
  • @Pierpaolo unfortunately I don't know how to do that--sorry! – Aaron Silverman Nov 14 '12 at 18:46
0

You can read and execute_script to enable jQuery:

  • First you can read the jquery from a jquery.js or jquery.min.js file.
  • Then using execute_script(jquery) to enable jquery dynamically.
  • Now you can interact with jquery.

here is some code in python, other language would be similar:

browser = webdriver.Firefox() # Get local session of firefox

with open('jquery.min.js', 'r') as jquery_js: #read the jquery from a file
    jquery = jquery_js.read()
    browser.execute_script(jquery)  #active the jquery lib

#now you can write some jquery code then execute_script them
js = """
    var str = "div#myPager table a:[href=\\"javascript:__doPostBack('myPager','%s')\\"]"
    console.log(str)
    var $next_anchor = $(str);
    if ($next_anchor.length) {
        return $next_anchor.get(0).click(); //do click and redirect
    } else {
        return false;
    }""" % str(25) 

success = browser.execute_script(js)
if success == False:
    break

PS: When I use Selenium to fetch some content from some website, they always ban me. Now you should use some proxy to go over it.
here is some code:

PROXY_HOST = "127.0.0.1"
PROXY_PORT = 8087
SOCKS_PORT = 8088

fp = webdriver.FirefoxProfile()

# Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
fp.set_preference("network.proxy.type", 1)

fp.set_preference("network.proxy.http", PROXY_HOST)
fp.set_preference("network.proxy.http_port", PROXY_PORT)
fp.set_preference("network.proxy.socks", PROXY_HOST)
fp.set_preference("network.proxy.socks_port", SOCKS_PORT)
fp.set_preference("network.proxy.ftp", PROXY_HOST)
fp.set_preference("network.proxy.ftp_port", PROXY_PORT)
fp.set_preference("network.proxy.ssl", PROXY_HOST)
fp.set_preference("network.proxy.ssl_port", PROXY_PORT)

fp.set_preference("network.proxy.no_proxies_on", "") # set this value as desired

browser= webdriver.Firefox(firefox_profile=fp) # with proxy
browser = webdriver.Firefox() # no proxy
browser.get("http://search.example.com") # Load page

elem = browser.find_element_by_id("query_box") # Find the query input
elem.send_keys(u'my query string') # send query string to the input
elem.submit() # submit the query form
Lei Cao
  • 457
  • 6
  • 13
0

You would need to define a new location strategy using the AddLocationStrategy method and will need to include jQuery in your user-extensions.js file.

PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72