Selenium 从 xpath 获取动态 ID [英] Selenium get dynamic id from xpath

查看:57
本文介绍了Selenium 从 xpath 获取动态 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Selenium RC 有没有办法从 xpath 中获取 id?

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

如果我有 xpath

/html/body/div/div//input

我想获取与 xpath 关联的所有节点的 id

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

推荐答案

您可以通过运行 javascript 来获得它,使用 this.browserbot.findElement('/html/body/div/div//input'):

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

当然,这取决于源语言,但应该是这样的(在 perl 中,未经测试):

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 根据注释,for 循环计数应从 1 开始并包括 $count,并且 findElement 行在输入前只需要一个正斜杠.

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 根据进一步的评论添加一个完全不同的想法:

EDIT2 Adding a completely different idea based on further comments:

附加到每个页面的 Selenium javascripts 包括一个名为 eval_xpath 的函数,该函数返回给定查询的 DOM 元素数组.听起来像你想要的吗?

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?

这是我认为 javascript 的样子(同样,未经测试):

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

这篇关于Selenium 从 xpath 获取动态 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆