硒自动化 - 寻找最佳xpath [英] Selenium automation- finding best xpath

查看:168
本文介绍了硒自动化 - 寻找最佳xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找避免使用'xpath位置'的xpaths。原因是,如果页面上有新对象并且移动了预期的xpath位置,则xpath可以更改并自动测试失败。



但是在一些网页上,这是我能找到的唯一xpath。例如,我正在寻找一个名为'FooBar'的标签。



如果使用Selenium IDE FireFox插件,我会得到:

  // td [12] / a / font 

如果我使用FirePath Firefox插件, :
$ b

  html / body / form / table [2] / tbody / tr / td [12] / font 

如果一个名为Hello,World的新选项卡添加到网页中(在FooBar选项卡之前),则FooBar选项卡将会更改并具有

  // td [13] / a / font 

你会建议做什么?



TY!

解决方案

而不是使用绝对xpath,你可以使用相关的xpath,它更短,更可靠。 >说

 < td id =FooBarname =FooBar> FooBar< / td> 

By.id(FooBar);
By.name(FooBar);

By.xpath(// td [text()='FooBar'])//完全匹配
By.xpath(// td [@ id ='FooBar' ])//带有任何属性值
By.xpath(// td [contains(text(),'oBar')])//与包含函数的部分匹配
By.xpath // td [starts-with(text(),'FooB')])//与startswith函数部分匹配

此博文可能是对你有用。


I am looking to avoid using xpaths that are 'xpath position'. Reason being, the xpath can change and fail an automation test if a new object is on the page and shifts the expected xpath position.

But on some web pages, this is the only xpath I can find. For example, I am looking to click a tab called 'FooBar'.

If I use the Selenium IDE FireFox plugin, I get:

//td[12]/a/font

If I use the FirePath Firefox plugin, I get:

html/body/form/table[2]/tbody/tr/td[12]/font

If a new tab called "Hello, World" is added to the web page (before FooBar tab) then FooBar tab will change and have an xpath position of

//td[13]/a/font

What would you suggest to do?

TY!

解决方案

Instead of using absolute xpath you could use relateive xpath which is short and more reliable.

Say

<td id="FooBar" name="FooBar">FooBar</td>

By.id("FooBar");
By.name("FooBar");

By.xpath("//td[text()='FooBar']")   //exact match
By.xpath("//td[@id='FooBar']")       //with any attribute value
By.xpath("//td[contains(text(),'oBar')]")   //partial match with contains function
By.xpath("//td[starts-with(text(),'FooB')]")  //partial match with startswith function

This blog post may be useful for you.

这篇关于硒自动化 - 寻找最佳xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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