Search code examples
seleniumxpathselenium-idekantu

Can't select nth element of same class with xpath / selenium IDE


Don't understand why the following loop doesn't work except for nth element with same class fails on the 2nd element (I'm presuming 1st element works because it's also the root in xpath):

{
  "Command": "storeEval",
  "Target": "$('.className').length",
  "Value": "max"
},
{
  "Command": "store",
  "Target": "1",
  "Value": "i"
},
{
  "Command": "while",
  "Target": "(${i} < ${max})",
  "Value": ""
},
{
  "Command": "echo",
  "Target": "Current value of i = ${i}",
  "Value": "i"
},
{
  "Command": "storeAttribute",
  "Target": "//a[contains(@class, 'className')][${i}]@href",
  "Value": "link"
},
{
  "Command": "endWhile",
  "Target": "",
  "Value": ""
}

For debugging, I tried to change ...[${i}] to [2] and it fails with both Kantu & Ranorex Selocity. However, From my reading of xpath / Selenium IDE documentation, this syntax should be correct. Any advice?

PS. For reference, the .className is actually .rf-project-cover__title on the page https://www.behance.net/search?field=132&content=projects&sort=published_date&time=week


Solution

  • I think you want to search, then extract i-th item, so you need brackets:

    (//a[contains(@class, 'className')])[${i}]
    

    for example:

    (//a[contains(@class, 'rf-project-cover__title')])[2]
    

    returns item with link text my portfolio