开发者

Finding text on page with Selenium 2

How can I check whether a given text string is present on the current page u开发者_如何学Gosing Selenium?


The code is this:

def elem = driver.findElement(By.xpath("//*[contains(.,'search_text')]")); 
if (elem == null)  println("The text is not found on the page!");


If your searching the whole page for some text , then providing an xpath or selector to find an element is not necessary. The following code might help..

Assert.assertEquals(driver.getPageSource().contains("text_to_search"), true);


For some reason, certain elements don't seem to respond to the "generic" search listed in the other answer. At least not in Selenium2library under Robot Framework which is where I needed this incantation to find the particular element:

xpath=//script[contains(@src, 'super-sekret-url.example.com')]


A simpler (but probably less efficient) alternative to XPaths is to just get all the visible text in the page body like so:

def pageText = browser.findElement(By.tagName("body")).getText();

Then if you're using JUnit or something, you can use an assertion to check that the string you are searching for is contained in it.

assertThat("Text not found on page", pageText, containsString(searchText));

Using an XPath is perhaps more efficient, but this way is simpler to understand for those unfamiliar with it. Also, an AssertionError generated by assertThat will include the text that does exist on the page, which may be desirable for debugging as anybody looking at the logs can clearly see what text is on the page if what we are looking for isn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜