Stanley Tan
Stanley Tan

Reputation: 433

How to store and verify text in Selenium Webdriver

How can I store a text from 1 page and verify whether that text is present on another page?

Upvotes: 0

Views: 4495

Answers (2)

Matthias
Matthias

Reputation: 318

As far as I know, there is no general 'findTextOnPage'-Methode for webdriver. I use a helper methode and the idea is the following:

WebDriver driver = new WebDriver(); //insert your favored webDriver
driver.get(urlOfPage1); //get Page1

//get Text...just you know your Webpage
String expectedText = YourMethodeToGetTheText();

driver.get(urlOfPage2); //change to Page2

//and now the 'hard' part:
WebElement body = driver.findElement(By.tagName("body"));
String bodyText = body.getText(); //get whole text of the body-Element
Assert.assertTrue(countTextPresentInString(expectedText, bodyText)>0);

and the Helper methode writes as:

public static int countTextPresentInString(String textToCheck, String text) {
    int count = 0;

    // search textToCheck in text
    while (text.contains(textToCheck)) {
        // if found, increment count
        count++;
        // proceed search just in that part, that hasn't been searched jet
        text = text.substring(text.indexOf(textToCheck) + textToCheck.length());
    }
    return count;
}

I hope this helps, if you have problems getting the text out of page1, then let me know.

Upvotes: 0

Nguyen Vu Hoang
Nguyen Vu Hoang

Reputation: 1570

Set text in 1st page into a variable then check that variable text exists on 2nd page

Here's sample code in Java

String expectedText = firstPage.textElement1.getText();

// Do something to get into second page

Assert.assertTrue(secondPage.isTextExist(expectedText));

Upvotes: 2

Related Questions