用于<label for ="x">的Selenium定位器

Joh*_*vin 11 testing selenium watin web-testing selenium-rc

使用ASP.NET,标签ID非常不稳定,所以为了使我的测试更加健壮,我想通过标签文本定位元素.我已经和WatiN玩了一些并且完美地做到了这一点但是现在这个项目似乎有点死了所以我认为在决定框架之前我也会考虑Selenium.

我有html看起来像这样

<label for="ctl00_content_loginForm_ctl01_username">Username</label>:
<input type="text" id="ctl00_content_loginForm_ctl01_username" />
Run Code Online (Sandbox Code Playgroud)

我不想输入:

selenium.Type("ctl00_content_loginForm_ctl01_username", "xxx");
Run Code Online (Sandbox Code Playgroud)

这太依赖于身份证.在WatiN我会写:

browser.TextField(Find.ByLabelText("Username")).TypeText("xxx");
Run Code Online (Sandbox Code Playgroud)

有没有办法在Selenium做到这一点?

小智 10

这有效:

//input[@id=(//label[text()="Username"]/@for)]
Run Code Online (Sandbox Code Playgroud)

说明:由于您正在寻找输入:

//input[@id=("ctl00_content_loginForm_ctl01_username")]
Run Code Online (Sandbox Code Playgroud)

用标签的属性值替换"ctl00_content_loginForm_ctl01_username":

//label[text()="Username"]/@for
Run Code Online (Sandbox Code Playgroud)


Pau*_*nan 7

我相信你可以用以下方法做到这一点:

selenium.Type(selenium.getAttribute("//label[text()='Username']/@for"), "xxx");
Run Code Online (Sandbox Code Playgroud)

text()='Username'位通过innerHTML获取所需的标签,然后/ @ for返回其"for"属性的值.

抬头:这没有经过测试(对此表示道歉!)但我认为它会起作用,基于IDE插件中的一些工具