How to find an element which has dynamic generating id

3.4k Views Asked by At

I need to click this element and upload a document, but here the id of the button is generating dynamically.

Element:

<button class="md-raised md-primary e-button-small md-button md-ink-ripple" type="button" ng-transclude="" aria-label="Approve" data-ng-file-select="onFileSelect($files, rule)" data-accept="*/*" multiple="multiple" onclick="document.getElementById(&quot;--ng-file-upload-0.6873237604099194&quot;).click()" id="e--ng-file-upload-0.6873237604099194" style="overflow: hidden;">
  <span class="ng-scope">Upload File</span>
  <div class="md-ripple-container" style=""></div>
</button>

Tried to find and click in below ways:

driver.findElement(By.cssSelector("button[id^='e--ng-file-upload']]")).click();  

driver.findElement(By.xpath("//button[contains(text(), 'Approve')]")).click();
  • I looked here as well.

and getting this error every time:

org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified (Session info: chrome=60.0.3112.113) (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 104 milliseconds

3

There are 3 best solutions below

0
On BEST ANSWER

You tried to get this item with text "Approve", but this is aria-label so you should do it like this using xpath (assuming that this is only button that have this label):

//button[@aria-label='Approve']

or with css selector:

button[aria-label=Approve]

0
On

Try this one for dynamic value

webDriver.findElement(By.xpath("//input[contains(@id, 'Somevalue')]"));
1
On

Your first selector has an extra ] at the end. It should be

driver.findElement(By.cssSelector("button[id^='e--ng-file-upload']")).click();

Your second selector... I don't know how it's supposed to work because "Approve" isn't contained in that element. You might try

driver.findElement(By.xpath("//button[contains(text(), 'Upload File')]")).click();

Other options:

driver.findElement(By.cssSelector("button[aria-label='Approve']")).click();
driver.findElement(By.xpath("//span[.='Upload File']")).click();