Wednesday, July 25, 2007

Finding the nth link in Selenium

One of the common things I do when testing is clicking on a link but it is not the first one with the text. Selenium only provides link= and if the recorder detects that you are not choosing the first link, it will put in an XPath expression that would not work if your links pass IDs (like in Curam). Fortunately though the extension system they provided we can add our own locators.

So I created a locator that allows me to put in links=Select[2] to choose the 3rd instance of the link Select (since it is zero base).

The code is pretty simple (I am testing the Insert Code plug-in for Windows Live Writer):

    PageBot.prototype.locateElementByLinks=
    function(text, inDocument) {
      var parsed = text.match(/^(.+)\[(\d+)\]$/)
      var textPortion = parsed[1]
      var index = parsed[2]
      var links =
        inDocument.getElementsByTagName("a");
      var c = 0;
      for (var i = 0; i < links.length; i++) {
        var text = links[i].innerText || links[i].text
        if (text == textPortion) {
          if (c == index) {
            return testElement
          }
          ++c
        }
      }
      return null;
    };

I made a slight modification to support Internet Explorer which does not support the "text" property.

0 comments: