How to find xPath for complicated tag without id name or value

Hi please help i have to find the xpath of this

<button _ngcontent-c27="" aria-label="VALIDATE" color="primary" fxflex="" mat-raised-button="" type="submit" class="mat-raised-button mat-primary" style="flex: 1 1 0%; box-sizing: border-box;"><span class="mat-button-wrapper"> VALIDATE </span><div class="mat-button-ripple mat-ripple" matripple=""></div><div class="mat-button-focus-overlay"></div></button>

but as i copy the xpath

/html/body/app-root/app-side-nav/mat-sidenav-container/mat-sidenav-content/main/app-otp/app-page-container/div/form/div/div/form/div/div[1]/button

then when i use it the console error NoSuchElementException

this is my code in selenium thanks in advace

driver.findElement(By.xpath("/html/body/app-root/app-side-nav/mat-sidenav-container/mat-sidenav-content/main/app-otp/app-page-container/div/form/div/div/form/div/div[1]/button")).click();

HTML Button please click

5 answers

  • answered 2018-11-08 06:09 koushick

    I hope these Three helps,

    //button[@type='submit']
    //*[contains(@type,'submit')]
    //button[contains(text(),'VALIDATE')]
    

    if Not try to post the HTML Code here so it will be helpful or, Check This Article try more on Yourself - https://www.guru99.com/xpath-selenium.html

  • answered 2018-11-08 06:41 ewwink

    find with multiple attribute use [@type=... and @class=...]

    //button[@type='submit' and @class='mat-raised-button mat-primary']
    

  • answered 2018-11-08 06:46 kobi

    There are two types of XPath: Absolute XPath. Relative XPath.

    while copying from console you cloud get Absolute XPath but the case is Absolute Xpath sometime got change according to the html change. you should use Relative Xpath to select element in selenium.

    let's check this site

    you definitely get answer

  • answered 2018-11-08 07:13 Waqar Nadir

    I think you are trying to automate website built on angular framework. In angular same div is used for multiple purpose. Developers just change binding and use the same button for multiple purpose.

    If you share complete webpage html it would be a great help.

    Just Check few things may be that help:

    1. Web element is visible on page.(css properties like display:none makes element disappear from page.It is still present in DOM but web driver can't find it)

    2. It is not loaded from jquery or ajax. if Yes, then Maybe you need to add webdriver wait for that.

    Exact solution is depending on your complete web page.

  • answered 2018-11-08 10:21 SDK_90

    First as a practice its better to use relative xpath, It will help you to reuse your code when new changes added.

    Second if there are no ID , Name or any specific element locator to handle, Then you have to try for attribute like

    `//button[contains(text(),'Validate')]`
    
    `//button[@type='submit']`
    

    //button[@aria-label='VALIDATE'] etc.