Recently we had a user ask us if it was possible to get Selenium to follow random links on a page.
Selenium can indeed click random links, but it requires some JavaScript tricks on the browser itself:

var browserJavaScript = “var temp = eval_xpath(‘//a\’, window.document);\n” +            “temp[Math.floor(Math.random() * temp.length)].innerHTML”;

var linkText = selenium.getEval(browserJavaScript);

selenium.click(“link=” + linkText);

What this does is create a JavaScript string that will run on the
browser itself. The JavaScript is written to retrieve all <a> links on the
page and then randomly select the innerHTML (text) for one of the
links on the page.

Once the link text is retrieved, it’s easy to tell Selenium to click that link.

The only time this won’t work is if there are <a> tags on the page
that don’t have text in them. For example, they might contain images,
and so the innerHTML returned will not work with the subsequent click
command, since it uses the “link=” locator, which expects only text.

We hope this quick little fix helps you perform more realistic tests.

3 Responses to “How to Get Selenium to Follow Random Links”

  1. Is this a .js selenium core user extension?
    Which file name has to be given?

    Regards

  2. Lorenzo,
    This is just generic code written. You’ll need to modify it a bit to work with your programming language (if you’re using Selenium RC) or with the Selenese language used by Selenium IDE.

    Patrick

  3. Ok thanks.

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

 

© 2012 The BrowserMob Blog Suffusion theme by Sayontan Sinha