this is not a logical question as such, but I really need to know what is the most effective way of writing xpath during selenium webdriver automation. Please explain a bit with few examples. Any help will be highly appreciated. Thanks
First: Ask your developers, if there could be unique identifiers in the tag parameters. Could be id, name or proprietal parameter. For example angular is using ng-* parameters for each object.
Study Xpath Tutorial (http://www.w3schools.com/xsl/xpath_intro.asp) to master your Xpath skills.
To create the particular xpath expression quickly, I use this steps:
- copypaste whole tag of the object you need to locate
[@behind the tag
- delete the rest in exception of parameter identifying the object
]on the end of xpath
You can combine xpath expressions to get specific path and distinguish between similar objects.
- Try to use Xpath axes (http://www.w3schools.com/xsl/xpath_axes.asp) as
/preceding-sibling::, ... etc. instead of full path. Developers often change structure of their code and structure of HTML can change a lot.
- In case parameter contains some string, use
- In case parameter starts with some string and rest is rubbish, use
- use dot
contains(.,"value")for text content of the web tag
For example for google code:
<form class="search-form" name="search" action="http://www.google.com/search" method="get"> <input id="sbi" class="search-input" type="search" x-webkit-speech="" value="" name="q">
You can write xpath:
Code could be shorter (
//input[@id="sbi"]) but in case id is changing during development, or there is more search dialogs/inputs on the page, it is practical to distinguish the position by parental element. Expression is more robust during development cycle and therefore you will not need to come back to it again.
Sometimes elements in the page are changed during developmnet, for example
<a> tags is replaced by
<li> tags, but parameters will stay. Consider to replace a tag by
* in your xpath expression.