3

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?

1
  • Do you want only table or any element which meets your conditions ? Commented Sep 28, 2016 at 16:25

3 Answers 3

7
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.

Sign up to request clarification or add additional context in comments.

4 Comments

Technically 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.
@JeffC True, I edited the answer in order to clarify.
Thank you. This was very helpful
I 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.
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')]

Comments

1

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']"));

1 Comment

CSS selector faster than xpath? Is there any proof for that claim?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.