...
- Start all of your XPath’s with //. This says to find an element anywhere in the HTML page regardless of where it is located and it is not dependent on other elements on the page
- Use ‘contains()’ instead of ‘=’ when searching for a text inside an element. The reason is that ‘=’ will fail if there are white spaces around the text you are looking for. Examples are:
- To find a td with text including Jill for example <td>Jill</td>, use this XPath: //td[contains(text(), ‘Jill’)]
- To find a link with text including MyText for example <a>MyText<a>, use this XPath: //a[contains(text(), ‘MyText’)]
- Do not use ‘following’ or ‘preceding’ by themselves as they do not work well with IE. following-sibling or preceding-sibling are fine to use.
More XPath examples:
XPath | Description |
---|---|
//input[@value='Continue' and @name='btnContinue'] | Select element of type input with attribute value matching 'Continue' and attribute name matching btnContinue |
//*[@id='someId'] | Select any html element with id equals to someId. Note that the id is case sensitive and is a whole match. |
//a[@href='someUrl'] | Select a link (Html anchor element) with attribute href matching 'someUrl'. Case sensitive |
//a[text()='Exact Match Case sensitive'] | Select a link (Html anchor element) with attribute visible text matching exactly 'Exact Match Case sensitive'. |
//a[contains(text(),'Partial Match Visible Text')] | Select a link (Html anchor element) with visible text containing text 'Partial Match Visible Text'. |
//a[@title='Some Title text'] | Select a link (Html anchor element) with attribute title matching 'Some Title text'. Case sensitive |
//*[contains(text(),'$SOME_DYNAMIC_PARAM')] /following::a[contains(text(),'Relative Link to previous link')] | Relative match. This is for dynamic elements where you locate the dynamic element and relative to that element you select the element you want to interact with. |
(//a[@href='Login.asp'])[1] | Find the first link that has the attribute href='Login.asp'. For second match use [2], third [3] and for [last() -1] for the one before the last. |
//table[@id='myTable']/tr[last()] | Select the last row of the table with id='myTable' |
//a[contains(@title,'bob')] | Find a link that contains 'bob' in its title attribute. |
//a[starts-with(@title,'bob')] | Find the link that has the title that starts with 'bob'. |