Q:

How to find element using contains in xpath

Can anyone please help me how to use contains in my xpath? My xpath changes all the time when users are added, so I can't find element using xpath.
This is my xpath: 
.//*[@id='contentText']/table/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr[9]/td/table/tbody/tr/td[1]/strong[2]

Changes when new user added: 
.//*[@id='contentText']/table/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr[10]/td/table/tbody/tr/td[1]/strong[2]

Please help me how to get it done.

A:

I have tested an ExtJS application. Most of the page element attributes are dynamic. They change not only when you add a new user or something, they change every time when you open the application. 
I have found the xpath expressions I get from the tools (Firebug etc.) is not very useful. Here is why:

hard to read
break easily
hard to debug

What I do instead, is rather to spend time looking at the HTML and identify possible unique attributes that are not dynamic and come up with my own expressions. If none of the attributes are static for a certain element, use any other element on the page that does have static attributes with the parent/child/sibling relations to locate.
I often use "contains", but there are more. Here are some examples:

multiple condition: //div[@class='bubble-title' and contains(text(), 'Cover')]
partial match: //span[contains(text(), 'Assign Rate')]
starts-with: //input[starts-with(@id,'reportcombo')]
value has spaces: //div[./div/div[normalize-space(.)='More Actions...']]
sibling: //td[.='LoadType']/following-sibling::td[1]/select"
more complex: //td[contains(normalize-space(@class), 'actualcell sajcell-row-lines saj-special x-grid-row-collapsed')]

Take a look at the W3C XSL Functions page for some more ideas.
Edit:
Link updated.
Edit 2:
XPATH changed

A:

You should be splitting the xpath to fetch individual tables for clarity sake.
I suggest the following:
// Get the content or container    
WebElement content = driver.findElement(By.id("contentText"));

//Get the table of users
WebElement tblUsers = content.findElement(By.xpath(".//table/tbody/tr[2]/td/table/tbody/tr/td[1]/table"));

// Get the rows which change always as and when users are added
WebElement allUsers = tblUsers.findElements(By.xpath(".//tbody/tr"));

// Loop through each row of users table
for(WebElement user : allUsers) {

   // Get the username
   WebElement username = user.findElement(By.xpath(".//td/table/tbody/tr/td[1]/strong[2]"));
   System.out.println("Username: " + username.getText());
}

