Selenium get dynamic id from xpath

半腔热情 提交于 2019-12-03 21:13:09

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(',');

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"));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!