Question

There's no isTextPresent in Selenium 2 (WebDriver)

What is the correct way to assert the existence of some text on a page with WebDriver?

Was it helpful?

Solution

I normally do something along the lines of:

assertEquals(driver.getPageSource().contains("sometext"), true);

assertTrue(driver.getPageSource().contains("sometext"));

OTHER TIPS

Page source contains HTML tags which might break your search text and result in false negatives. I found this solution works much like Selenium RC's isTextPresent API.

WebDriver driver = new FirefoxDriver(); //or some other driver
driver.findElement(By.tagName("body")).getText().contains("Some text to search")

doing getText and then contains does have a performance trade-off. You might want to narrow down search tree by using a more specific WebElement.

I know this is a bit old, but I found a good answer here: Selenium 2.0 Web Driver: implementation of isTextPresent

In Python, this looks like:

def is_text_present(self, text):
    try: el = self.driver.find_element_by_tag_name("body")
    except NoSuchElementException, e: return False
    return text in el.text

Or if you want to actually check the text content of a WebElement you could do something like:

assertEquals(getMyWebElement().getText(), "Expected text");

Selenium2 Java Code for isTextPresent (Selenium IDE Code) in JUnit4

public boolean isTextPresent(String str)
{
    WebElement bodyElement = driver.findElement(By.tagName("body"));
    return bodyElement.getText().contains(str);
}

@Test
public void testText() throws Exception {
    assertTrue(isTextPresent("Some Text to search"));
}

The following code using Java in WebDriver should work:

assertTrue(driver.getPageSource().contains("Welcome Ripon Al Wasim"));
assertTrue(driver.findElement(By.id("widget_205_after_login")).getText().matches("^[\\s\\S]*Welcome ripon[\\s\\S]*$"));

I have written the following method:

public boolean isTextPresent(String text){
        try{
            boolean b = driver.getPageSource().contains(text);
            return b;
        }
        catch(Exception e){
            return false;
        }
    }

The above method is called as below:

assertTrue(isTextPresent("some text"));

It is working nicely.

Testing if text is present in Ruby (a beginners approach) using firefox as target browser.

1) You need of course to download and run selenium server jar file with something like:

java - jar C:\Users\wmj\Downloads\selenium-server-standalone-2.25.0.jar

2) You need to install ruby, and in its bin folder, run commands to install additional gems:

gem install selenium-webdriver
gem install test-unit

3) create a file test-it.rb containing:

require "selenium-webdriver"
require "test/unit"

class TestIt < Test::Unit::TestCase

    def setup
        @driver = Selenium::WebDriver.for :firefox
        @base_url = "http://www.yoursitehere.com"
        @driver.manage.timeouts.implicit_wait = 30
        @verification_errors = []
        @wait = Selenium::WebDriver::Wait.new :timeout => 10
    end


    def teardown
        @driver.quit
        assert_equal [], @verification_errors
    end

    def element_present?(how, what)
        @driver.find_element(how, what)
        true
        rescue Selenium::WebDriver::Error::NoSuchElementError
        false
    end

    def verify(&blk)
        yield
        rescue Test::Unit::AssertionFailedError => ex
        @verification_errors << ex
    end

    def test_simple

        @driver.get(@base_url + "/")
        # simulate a click on a span that is contained in a "a href" link 
        @driver.find_element(:css, "#linkLogin > span").click
        # we clear username textbox
        @driver.find_element(:id, "UserName").clear
        # we enter username
        @driver.find_element(:id, "UserName").send_keys "bozo"
        # we clear password
        @driver.find_element(:id, "Password").clear
        # we enter password
        @driver.find_element(:id, "Password").send_keys "123456"
        # we click on a button where its css is named as "btn"
        @driver.find_element(:css, "input.btn").click

        # you can wait for page to load, to check if text "My account" is present in body tag
        assert_nothing_raised do
            @wait.until { @driver.find_element(:tag_name=>"body").text.include? "My account" }
        end
        # or you can use direct assertion to check if text "My account" is present in body tag
        assert(@driver.find_element(:tag_name => "body").text.include?("My account"),"My account text check!")

        @driver.find_element(:css, "input.btn").click
    end
end

4) run ruby:

ruby test-it.rb
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top