Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
Dark Star1 Avatar asked Jul 06 '15 14:07

Dark Star1


People also ask

Can we find an element using element ID in Selenium?

We can find an element using the attribute id with Selenium webdriver using the locators - id, css, or xpath. To identify the element with css, the expression should be tagname[id='value'] and the method to be used is By. cssSelector. To identify the element with xpath, the expression should be //tagname[@id='value'].

How can we locate an element by only partially matching its attributes value in xpath?

We can identify elements by partially comparing to its attributes in Selenium with the help of regular expression. In xpath, there is contains () method. It supports partial matching with the value of the attributes. This method comes as useful while dealing with elements having dynamic values in their attributes.

Which is the best way to locate an element in Selenium?

ID locator in Selenium is the most preferred and fastest way to locate desired WebElements on the page. ID Selenium locators are unique for each element in the DOM. Since IDs are unique for each element on the page, it is considered the fastest and safest method to locate elements.


2 Answers

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; } 
like image 116
alecxe Avatar answered Sep 22 '22 00:09

alecxe


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

like image 24
Cathal Avatar answered Sep 21 '22 00:09

Cathal