Is it possible to locate element by partial id match in Selenium

I am trying to locate elements with generated ids wherein some part of the ID is known; for example:

id="page_x002e_x0023_default-create-firstname"

in which the last 3 words (_default-create-firstname) are known but anything preceding that is subject to change. Is this possible?


Solution 1:

You can apply an ends-with CSS selector:

By.cssSelector("[id$=default-create-firstname]")

Update

Some time went by since the answer was posted. Here some update from the linked mozilla developer page and comments below:

New use By.css instead of By.cssSelector

By.css("[id$=default-create-firstname]")

Also see the four possibilities of

  • beginning with
  • anywhere inside
  • anywhere inside regardless capitalization
  • end with

/* Internal links, beginning with "#" */
a[href^="#"] {
  background-color: gold;
}

/* Links with "example" anywhere in the URL */
a[href*="example"] {
  background-color: silver;
}

/* Links with "insensitive" anywhere in the URL,
   regardless of capitalization */
a[href*="insensitive" i] {
  color: cyan;
}

/* Links that end in ".org" */
a[href$=".org"] {
  color: red;
}

Solution 2:

If you want to go down the xpath route then you could use contains(), like this:

//*[contains(@id,'_default-create-firstname')]

This will search the entire page for an id that contains the text "_default-create-firstname". It can be easily made more specific