Reputation: 1
I have this code
WebElement element = driver.findElement(By.id("j_idt9:usuario"));
I want to know how I can use XPath to search for a specific ID. In this case, I want to search for the "usuario" portion because the "j_idt9" portion changes. I know that it can be done using a CSS Selector but I am required to use XPath.
Upvotes: 0
Views: 92
Reputation: 25542
You should tell your professor that CSS selectors are not just for classes... and if s/he really did say that, they should be embarrassed and go do some reading. They can start with these two references:
https://www.w3.org/TR/selectors/#selectors
https://saucelabs.com/resources/articles/selenium-tips-css-selectors
If you have to use XPath, it would look like
"//*[ends-with(@id, 'usuario')]"
You'd be better off using a CSS selector because it's faster and has better, more consistent browser support. It would look like
"[id$='usuario']"
In general, your locator strategy should look like this...
By.xpath should only be used when the other methods won't work. Cases like you need to find an element by the text it contains or you have to do some parent/child shifts that CSS can't do.
Upvotes: 2