Search code examples
javaseleniumselenium-webdriverfindelement

find element in selenium by sub string


I am coding in java with selenium and i am stuck. I have to find element by ID, the Id of the element is like this "msi_num_create-copy" (the num is changing every time), there is a way to find the element by part of the Id?


Solution

  • yes you would need to use either css selector or xpath :

    XPATH would be :

    //*[contains(@id, '_create-copy') and starts-with(@id, 'msi')]
    

    and use it like this :

    WebElement someEle = driver.findElement(By.xpath("//*[contains(@id, '_create-copy') and starts-with(@id, 'msi')]"));
    someEle.click(); or someEle.sendKeys("some string");