☰ See All Chapters |
Selenium relative XPath using attribute
XPath expression can be written using attribute of the web element. Based on the situation, we would use either single attribute or multiple attributes to find an element on a web page. Using single attribute in xpath expression, if it returns one matching element, then we would use single attribute only. In case, by using single attribute in xpath expression, if it returns multiple matching elements on the web page, then we would go for using multiple attributes in the xpath expression till we get one matching element.
XPath syntax using attribute
Using single attribute | //tagname[@attributeName='attributeValue'] |
Using multiple attribute | And condition //tagName[@attributeName1='attributeValue1'] [@attributeName2='attributeValue2'] //tagName[@attributeName1='attributeValue1' and @attributeName2='attributeValue2'] Or condition //tagName[@attributeName1='attributeValue1'] | //tagName[@attributeName2='attributeValue2'] //tagName[@attributeName1='attributeValue1' or @attributeName2='attributeValue2'] |
Negating attribute | //tagname[not(@attributeName='attributeValue')] |
Considering the below sample html code, below are the different relative XPath examples using attribute
<html> </head> <body> <table align="center" width=90% cellspacing="2" cellpadding="2" > <tr> <td>Row 1 : </td> <td><input type="text" id="xyz"></td> </tr> <tr> <td>Row 2 : </td> <td><input type="text" name="lmn"></td> </tr> <tr> <td>Row 3 : </td> <td><input type="checkbox" name="klm" class = "pqr"></td> </tr> <tr> <td>Row 4 : </td> <td><input type="checkbox" name="klm" ></td> </tr> <tr> <td>Row 5 : </td> <td><input type="checkbox" class = "pqr"></td> </tr> <tr> <td>Row 6 : </td> <td><input type="password" class = "password"></td> </tr> <tr> <td>Row 7 : </td> <td><input type="password" ></td> </tr> </table> </body> </html> |
Relative XPath expressions using attributes | Matching Element |
xpath=//input[@id='xyz'] | Row 1 Input |
xpath=//input[@name='lmn'] | Row 2 Input |
xpath=//input[@type='checkbox' and @name='klm' and @class='pqr'] | Row 3 Input |
xpath=//input[@type='checkbox'] [@name='klm'] [@class='pqr'] | Row 3 Input |
xpath=//input[@type='checkbox' and @name='klm' and not(@class='pqr')] | Row 4 Input |
xpath=//input[@type='checkbox'] [@name='klm'] [not(@class='pqr')] | Row 4 Input |
xpath=//input[@type='checkbox' and not(@name='klm') and @class='pqr'] | Row 5 Input |
xpath=//input[@type='checkbox'] [not(@name='klm')] [@class='pqr'] | Row 5 Input |
xpath=//input[@type='password' and @class ='password'] | Row 6 Input |
xpath=//input[@type='password'] [@class='password'] | Row 6 Input |
xpath=//input[@type='password' and not(@class='password')] | Row 7 Input |
xpath=//input[@type='password'] [not(@class='password')] | Row 7 Input |
You can write the script and test these using our Test Page
All Chapters