Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

html - Selenium automation- finding best xpath

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...