Selenium:是否可以将 xpath 与变量连接起来?

发布于 2024-07-11 05:19:45 字数 275 浏览 6 评论 0原文

我的元素的 xpath 变得极其难以阅读。

//div[@id='main_content']/div[2]/div[2]/div[2]/div[4]/table/tbody/tr[2]/td/form/fieldset/p[1 ]/input

如果我可以将其中的大部分存储为变量并稍后像这样使用它,那就太好了:

| 断言元素存在 | ${myForm} 。 /fieldset/p[1]/输入 |

这样的事情可能吗? 这将使我的测试更容易阅读!

The xpath of my elements are becoming extremely hard to read.

//div[@id='main_content']/div[2]/div[2]/div[2]/div[4]/table/tbody/tr[2]/td/form/fieldset/p[1]/input

It would be nice if I could store most of that as a variable and use it later like this:

| assertElementPresent | ${myForm} . /fieldset/p[1]/input |

Is something like this possible? It would make my tests so much easier to read!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

内心激荡 2024-07-18 05:19:45

确实应该将selenium 表达式锚定在元素的ID 中。 两个月后,没有人会知道 xpath 指向什么,特别是如果测试在您需要找出答案时被破坏了。 我们经常向元素添加 id 只是为了使测试更容易。 我们已经学会接受我们以特殊的方式编写 Java 代码以使其可测试,并且我认为这对于 HTML 来说也是可以的。

You really should anchor your selenium espressions in ID's of elements instead. In 2 months, no-one is going to have the faintest idea of what the xpath points to, especially if the test is broken at the time you need to find out. We routinely add id's to element just to make testing easier. We've learned to accept that we write java code in a special way to make it testable, and I think it's ok for HTML too.

逆流 2024-07-18 05:19:45

你可以这样写:

store | //div[@id='main_content']/div[2]/div[2]/div[2]/div[4]/table/tbody/tr[2]/td/form | myForm
assertElementPresent | xpath=${myForm}/fieldset/p[1]/input

然而,正如 Krosenvold 所说,长 xpath 可能非常脆弱。 如果您担心代码的可读性,并希望所有定位器都在一个文件中,您可以在其中进行级联更改,那么您可能需要考虑使用 UI 元素映射。

You could just write:

store | //div[@id='main_content']/div[2]/div[2]/div[2]/div[4]/table/tbody/tr[2]/td/form | myForm
assertElementPresent | xpath=${myForm}/fieldset/p[1]/input

As Krosenvold said, however, long xpaths can be pretty fragile. If your concerned about readability in your code, and want all your locators in one file where you can make cascading changes, you might want to consider using an UI-Element map.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文