2011/03/15

Moving to Selenium 2 on WebDriver, Part No.1

I am in the process of trying to move code of some test to the Selenium 2 WebDriver. This is the first part of series of short articles about how to "translate" old Selenium API to the WebDriver-based one.

In following, let's state that xpathLocator is Selenium 1 locator, while xpathFinder is more or less By.xpath(xpathLocator),selenium is instance of Selenium, driver is instance of WebDriver (FirefoxDriver).

Is an element present on a page ?

Selenium 1:
selenium.isElementPresent(xpathLocator);

Selenium 2:
driver.findElements(xpathFinder).size()>0;

Get HTML source of a page

Selenium 1:
selenium.getHtmlSource();

Selenium 2:
driver.getPageSource();

Is a text present on a page ?

Selenium 1:
selenium.isTextPresent(text);

Selenium 2:
driver.getPageSource().contains(text);

Go to relative URL
The relativeUrl is URL relative to initial URL, i.e. without the "http://hostname".

Selenium 1:
selenium.open(relativeUrl);

Selenium 2:
driver.get( initialUrl + relativeUrl );

This call is blocking, i.e. further processing is stopped until the page is loaded.

To open an URL relative to the currently used  one, use  driver.getCurrentUrl():
driver.get( driver.getCurrentUrl() + relativeUrl );

Is an element visible on a page?

Selenium 1:
selenium.isVisible(location)

Selenium 2:
driver.findElement(location) instanceof RenderedWebElement
((RenderedWebElement)driver.findElement(location)).isDisplayed()

3 comments:

  1. There is a problem with your list above.

    selenium.isTextPresent(text);

    is not the same as

    driver.getPageSource().contains(text);

    as the first one removes all HTML tags, but the second doesn't. So if text is "Hello abc", but on the page it is actually "Hello <em>abc</em>", the first one would work, but the second wouldn't.

    I might be wrong here as I don't have a working Selenium 1 anymore to test it.

    ReplyDelete
  2. Agreed. I'm still looking for a reliable isTextPresent replacement in Selenium2

    ReplyDelete
  3. During the transition of our code base all the occurrences of isTextPresent() were replaced with custom waitForElementVisible() - it better reflected desired semantics for our pages full of AJAX.

    I wrote also wait for JavaScript expression to evaluate to true or wait for element attribute (or content) to have given value - I believe it could be used to reimplement isTextPresent() if it had been demanded.

    ReplyDelete