对于 ASP.NET,标签 ID 非常不稳定,因此为了使我的测试更加稳健,我想通过标签文本来定位元素。我用 WatiN 玩过一些,它完美地做到了这一点,但这个项目现在似乎已经死了,所以我想在决定框架之前我也应该研究一下 Selenium。
我的 html 看起来像这样,
<label for="ctl00_content_loginForm_ctl01_username">Username</label>:
<input type="text" id="ctl00_content_loginForm_ctl01_username" />
但我不想输入:
selenium.Type("ctl00_content_loginForm_ctl01_username", "xxx");
这太依赖 ID 了。在 WatiN 中,我会写:
browser.TextField(Find.ByLabelText("Username")).TypeText("xxx");
有没有办法在 Selenium 中做到这一点?
With ASP.NET the tag IDs are pretty volatile so to make my tests more robust I want to locate elements by their label texts. I have played some with WatiN and it does this perfectly but that project seem kind of dead nowadays so I thought I'd look into Selenium as well before I decide on a framework.
I have html that looks something like this
<label for="ctl00_content_loginForm_ctl01_username">Username</label>:
<input type="text" id="ctl00_content_loginForm_ctl01_username" />
I don't want to type:
selenium.Type("ctl00_content_loginForm_ctl01_username", "xxx");
That is too reliant on the ID. In WatiN I'd write:
browser.TextField(Find.ByLabelText("Username")).TypeText("xxx");
Is there a way to do this in Selenium?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这有效:
说明:由于您正在查找输入:
将“ctl00_content_loginForm_ctl01_username”替换为标签的属性值:
This works:
Explanation: Since you are looking for the input:
replace the "ctl00_content_loginForm_ctl01_username" by the attribute's value of the label:
我相信您可以通过以下方式执行此操作:
text()='Username' 位通过其innerHTML 获取您想要的标签,然后/@for 返回其“for”属性的值。
注意:这尚未经过测试(对此表示歉意!),但我认为它会起作用,基于 IDE 插件中的一些工具
I believe you can do this with the following:
The text()='Username' bit gets the label you want by its innerHTML, then the /@for gives you back the value of its "for" attribute.
Heads up: this is not tested (apologies for that!) but I think it'll work, based on some tooling around in the IDE plugin
好吧,这可能已经有一岁了,但是他们嘿。这将选择包含文本“用户名”的标签下的第一个输入。
我通常更喜欢使用 contains() ,因为我发现某些浏览器会在偶尔的元素中添加烦人的空格:
请注意,输入之前的单斜杠表示它只会向下查找一级,其中双斜杠将检查标签下的所有级别。使用 XPather for Firefox 来创建和检查您的 XPath,它非常有用。
Ok, this may be a year old but what they hey. This will select the first input under a label containing the text 'Username'.
I generally prefer using contains() as I find that some browsers are adding annoying spaces into the occasional element:
Note that the single slash before input denotes it will only look one level down, where the double slash would check all levels under the label. Use XPather for Firefox to create and check your XPaths, it's very useful.
是的,您可以使用 XPath、CSS 或 DOM 定位器来识别您的元素。在此示例中,您的 XPath 可能类似于 //lable[@for='ctl00_content_loginForm_ctl01_username'] 来标识该特定标签。
Yes, you can use XPath, CSS or DOM locators to identify your element. In this example your XPath could look like //lable[@for='ctl00_content_loginForm_ctl01_username'] to identify that particular label.