Reflux
Reflux

Reputation: 2949

Selenium get dynamic id from xpath

Is there a way in Selenium RC to get the id from the xpath?

If I have the xpath

/html/body/div/div//input

I want to get the id of all the nodes associated to the xpath

Upvotes: 2

Views: 9911

Answers (2)

Dave Hunt
Dave Hunt

Reputation: 8223

You can use getAttribute in combination with getXpathCount.

A Selenium 1 example in Java would be:

int inputs = selenium.getXpathCount("/html/body/div/div/descendant::input").intValue();
for (int i=1; i<=inputs; i++) {
    System.out.println(selenium.getAttribute("/html/body/div/div/descendant::input[" + i + "]@id"));
}

A Selenium 2 example in Java would be:

List<WebElement> inputs = driver.findElements(By.xpath("/html/body/div/div/descendant::input"));
for (WebElement input : inputs) {
    System.out.println(input.getAttribute("id"));
}

Upvotes: 7

Ryley
Ryley

Reputation: 21226

You can get that by running a javascript, using this.browserbot.findElement('/html/body/div/div//input'):

Of course, this depends on the source language, but it would be something like this (in perl, untested):

#first count the number of inputs with ids
my $count = $selObj->get_xpath_count('/html/body/div/div//input[@id]');

#build a javascript that iterates through the inputs and saves their IDs
my $javascript;
$javascript .= 'var elements = [];';
$javascript .= "for (i=1;i<=$count;i++)";
$javascript .= "  elements.push(this.browserbot.findElement('/html/body/div/div/input['+i+']').id);";
#the last thing it should do is output a string, which Selenium will return to you
$javascript .= "elements.join(',');";

my $idString = $selObj->get_eval($javascript);

I always thought there should be a more direct way to do this, but I haven't found it yet!

EDITED based on the comments, the for loop count should start from 1 and include $count, also the findElement line only needs one forward-slash before input.

EDIT2 Adding a completely different idea based on further comments:

Selenium's javascripts that get attached to every page include a function called eval_xpath that returns an array of DOM elements for a given query. Sounds like what you want?

Here's what I think the javascript would look like (again, untested):

var elements = eval_xpath('/html/body/div/div//input',this.browserbot.getCurrentWindow().document);
var results = [];
for (i=0;i<elements.length;i++){
  results.push(elements[i].id);
}

results.join(',');

Upvotes: 0

Related Questions