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?
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'].
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.
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.
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
/* 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; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With