Is it possible to search for a dynamic button if the beginning of he ID is always the same?

128 views Asked by At

I am using Selenium in some automation testing. On a certain page i need to click a button. This same page is used multiple times and when i originally tried to use the full xpath it would work on one of the pages but not the other. The full xpath for each page is slightly different so i dont want to use that.

The xpath of the button looks like this

.//*[@id='approve-gen8149262f2cdc49958632185c33b8e82f']

On both pages the id always starts with approve and then gets some generated numbers.

I am wondering if there is a way to search for just a section of the id so i can look for "approve" in order to find the button i need to click.

I have tried a number of things with no luck thus far.

4

There are 4 answers

0
ParasuRam On

You can also use the xpath with contains. for eg. //*[contains(@id, 'approve-gen')] Make sure that there are no other locators with id starts with 'approve-gen'.

0
LaurentG On

Using XPath, you can select an element where one of its attribute begins with a given string. For instance:

//*[starts-with(@id, "approve-gen")]

See also:

1
Robbie Wareham On

You can also use CSS selector:

[id^="approve"]
0
user3487861 On

Use Step 1: From the Given Info I have assumed the CSS Selector as

css=button[id*='approve-gen']

Also look for the Other Attributes of button that will bring uniqueness.

Step 2:

Perform Click on the button

driver.findElement(By.cssSelector("button[id*='approve-gen']")).click();