Selenium check if attribute contains part of a string in java
Solution 1
driver.findElement(By.xpath("//table[@title='not derp' and contains(@id, 'yyy')]"));
will find the first element which matches your search criteria which would be <table id = "yyytable2" title = 'not derp'>
of your HTML snippet.
Solution 2
There are a whole host of relational and logical operators you can use. In this case, assuming you're looking for the table element, you can use: //table[@title='not derp' and contains(@id,'yyyy')]
Solution 3
I would like to find an element by xpath where the @title = not derp and the @id contains yyy
I would suggest you cssSelector
instead, because using By.cssSelector()
to locate an element is much faster than By.xpath()
in performance. So you should try as below :-
driver.findElement(By.cssSelector("table[id *= 'yyy'][title = 'not derp']"));
Jrawr
Updated on June 04, 2022Comments
-
Jrawr almost 2 years
So I have a webpage where the Id's of certain elements are generated dynamically with certain parts changing and certain parts being constant like so:
<div id= "xxxdiv" title= 'this title'> <p id = "xxxp"> <table id = "xxxtable" title = 'not derp'> <div id = "yyyydiv"> <table id = "yyytable" title= 'derp'> <table id = "yyytable2" title = 'not derp'> <table id = "zzztable" title = derp>
I'm trying to do some dynamic lookups on the page that can look for a given element where the id contains a known value. For instance, I do not always know how many nested elements might exist so the number that gets generated on the end can vary. So I would like to find an element by xpath where the @title = not derp and the @id contains yyy. How can I accomplish this?
-
JeffC over 7 yearsTechnically this finds the first
TABLE
element... not just the first element. Depends on what OP wants. It can be easily switched to"//*[@title..."
to make it generic. -
Würgspaß over 7 years@JeffC True, I edited the answer in order to clarify.
-
Jrawr over 7 yearsThank you. This was very helpful
-
Jrawr over 7 yearsI wasn't sure if contains(@id, 'yyy') looked for an element that contained a matching id or looked for an id that contained the provided text.
-
m02ph3u5 over 4 yearsCSS selector faster than xpath? Is there any proof for that claim?