2

How can I confirm the text "FIND ME PLEASE" is displayed on a webpage using Java? Please refer to the HTML code below:

<table width="600" border="0" cellspacing="5" cellpadding="0"> <tr><td class="fontlargebold" align="center">&nbsp;FIND ME PLEASE&nbsp;</td></tr> </table> 

The difficulty resides with the HTML code not having attributes such as ID, name, value...etc. I attempted to use xpath (By.xpath("//*[text()=[contains('FIND ME PLEASE')]]")) )but I don't think it's correct...

1
  • You're not using the contains-function correctly. contains needs two arguments, first the content to be searched and second the searchstring. See the W3C Specifications for contains() for some examples. Commented Jul 22, 2013 at 15:32

2 Answers 2

3

Your XPath is indeed wrong.

Use

By.xpath("//*[contains(text(), 'FIND ME PLEASE')]") 

The whole Java code for a method doing your job:

public boolean isTextPresent(String text) { List<WebElement> foundElements = driver.findElements(By.xpath("//*[contains(text(), '" + text + "')]")); return foundElements.size() > 0; } 
Sign up to request clarification or add additional context in comments.

2 Comments

It worked! I really appreciate the quick response. For curiosity sake, why did the path have to be (..., '"+ text + "'), as compared to just (..., text)? Thank you.
@user2607278 Because in "//*[contains(text(), text)]", text is not a variable name, but a string. Tha construct I have there concatenates the XPath expression with the contents of the text variable. Search Java String concatenation. No problem for vote, if the answer was helpful, accept it instead!
0

If you're interested whether this text somewhere occurs, and also may contain other markup, go for

contains(/html/body, 'FIND ME PLEASE') 

which will return a boolean value when the content is found.

If you need to return an element instead a boolean value, you can do that, too:

/html/body[contains(., 'FIND ME PLEASE')] 

2 Comments

While this is true, in the current context (Selenium WebDriver), there's no method that would accept an XPath expression and return a boolean value. Without workarounds, we can only ask for nodes.
Didn't know that, but only changes the query a little bit, not the concept behind.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.