简体   繁体   English

使用动态ID定位元素

[英]Locating Elements with dynamic id

If you have an element in a page as follows (there are multiple select elements) 如果页面中有如下元素(有多个选择元素)

<select size="1" name="j_id0:j_id2:j_id37:j_id38:0:j_id41">
<select size="1" name="j_id0:j_id2:j_id37:j_id38:1:j_id41">

With the only identifier being its name but the name will change dynamically how would you locate it in selenium(java) without referencing the name? 使用唯一的标识符作为其名称,但是名称将动态更改,您如何在不引用名称的情况下在selenium(java)中找到它?

I am currently using the xpath as follows 我目前正在使用xpath如下

/html/body/div/div[2]/table/tbody/tr/td[2]/form/div[3]/div/div/div/div[2]/div[1]/span[3]/select

Problem being if anything on the page changes this xpath will be break. 问题是,如果页面上的任何内容发生更改,此xpath都会中断。

Are there any better alternative ways which are less easily broken? 有没有更好的替代方法不那么容易破解?

You've correctly noted that the presented XPath is quite fragile. 您已经正确地注意到,所提供的XPath非常脆弱。 It would be also useful to see the complete HTML of the page, or, at least, preceding and following elements of the select element. 查看页面的完整HTML或至少select元素的前后元素也将很有用。 From what we have now, you can rely on the part of the name attribute: 从现在开始,您可以依靠name属性的一部分:

//select[contains(@name, "j_id")]

I suppose not all ids on your site are dynamic. 我想并不是您网站上的所有ID都是动态的。

So there is definitely a cleaner way to write your locator. 因此,绝对有一种更干净的方式来编写定位器。

Provide some more of your html structure and I can give you more details. 提供更多的html结构,我可以为您提供更多详细信息。

Give a try.. These select tags must have some labels associated. 试试看。这些选择标签必须具有一些关联的标签。 Use following-siblings and ancestor xpath axis to locate your element relative to the labels. 使用跟随兄弟姐妹和祖先xpath轴相对于标签定位元素。

http://www.w3schools.com/xpath/xpath_axes.asp http://www.w3schools.com/xpath/xpath_axes.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM