Using PhantomJS to read a file and output to a file.

1. Download PhantomJS from here: http://phantomjs.org/

2. On Windows, unzip the archive to your drive and put the path to the phantonjs.exe in your Environment Variables Path:

C:\phantomjs-1.9.0-windows\;

3. Save this as readFile.js

/*jslint indent: 4*/
/*globals document, phantom*/
'use strict';

var fs = require('fs'),
    system = require('system');

if (system.args.length < 2) {
    console.log("Usage: readFile.js FILE");
    phantom.exit(1);
}

var content = '',
    f = null,
    lines = null,
    eol = system.os.name == 'windows' ? "\r\n" : "\n";

try {
    f = fs.open(system.args[1], "r");
    content = f.read();
} catch (e) {
    console.log(e);
}

if (f) {
    f.close();
}

if (content) {
    lines = content.split(eol);
    for (var i = 0, len = lines.length; i < len; i++) {
        console.log(lines[i]);
    }
}

phantom.exit();

4. Execute it like this:

phantomjs readFile.js filetoread > somefile.txt

You can use this script to open log files, parse out important lines, and save to an HTML file for instance.


Two ways to assert text with WebDriver

You can use this:

driver.getPageSource().contains(pattern)

or find the element with the text and assert that it is visible.

WebElement el = driver.findElement(By.xpath("//*[contains(.,'" + pattern + "')]"));

I find that the latter works better in most cases. I wrap it in a try/catch block to grab any NoSuchElementException.


Handling JavaScript Alert in WebDriver

This is a very helpful example of how to handle Javascript alert boxes with WebDriver.

via Handling JavaScript Alert in WebDriver.


Select element with jQuery where the id contains specific text.

I have needed to do this on occasion with long auto-generated ids.

$j("[id$='logActivitiesCheckbox']");

To get a WebElement object back from WebDriver I use this method:

  public WebElement getWebElementFromJquery(String jQuery) {
    WebElement jqElement = null;
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String query = "return " + jQuery+ ".get(0);";
    try {
      jqElement = (WebElement) js.executeScript(query);
    } catch (Exception e) {
      logger.error("jQuery() " + e.getMessage());
    }
    return jqElement;
  }

Two useful methods for finding elements with generic locator strings

  
public WebElement findElement(String identifier) {
    WebElement el = null;
    try {
      if (identifier.indexOf("//") > -1) {
        el = driver.findElement(By.xpath(identifier));
      } else if (identifier.indexOf("link=") > -1) {
        String linkText = identifier.split("=")[1];
        el = driver.findElement(By.linkText(linkText));
      } else if (identifier.indexOf("$") > -1) {
        el = getWebElementFromJquery(identifier);
      } else if (identifier.indexOf(">") > -1 || identifier.indexOf(".") > -1) {
        el = driver.findElement(By.cssSelector(identifier));
      } else {
        el = driver.findElement(By.id(identifier));
      }
    } catch (Exception e) {
      logger.error("findElement() " + e.getMessage());
    }
    return el;
  }
 
  public List findElements(String identifier) {
    List el = null;
    try {
      if (identifier.indexOf("//") > -1) {
        el = driver.findElements(By.xpath(identifier));
      } else if (identifier.indexOf("link=") > -1) {
        String linkText = identifier.split("=")[1];
        el = (List) driver.findElements(By.linkText(linkText));
      } else {
        el = driver.findElements(By.id(identifier));
      }
    } catch (Exception e) {
      logger.error("findElements() " + e.getMessage());
    }
    return el;
  }


Find Web Element By Text

A td tag with the text “Settings” for example:

//td[contains(text(), 'Settings')]

Another example:

//div[contains(.,'Some Text')]

Sometimes there are cross-browser problems with using XPath. One solution is to get all elements with a specific tag name, and iterate through the list to match the values of specific attributes.


Selenium WebDriver on Firefox: Working with Add-Ons

Selenium WebDriver on Firefox: Working with Add-Ons.

via Selenium WebDriver on Firefox: Working with Add-Ons.


Switching to a new tab in WebDriver

public void switchWindow() throws NoSuchWindowException{
       try {
           Set handles = driver.getWindowHandles();
           String current = driver.getWindowHandle();
           handles.remove(current);
           String newTab = handles.iterator().next();
           driver.switchTo().window(newTab);
        } catch( Exception e ) {
            logger.logError(e.getMessage());
        }
}

Getting the return value from an anonymous JavaScript function with Webdriver

I needed to get the return value of a JavaScript function executed through WebDriver. Specifically, I needed to get the text from a WYSIWYG editor called TinyMCE. Here was my solution. Example:

String javascript = " ( function getText() { " +
" for(i=0; i < window.frames.length; i++) { " +
" if( window.frames[i].document.getElementById('tinymce') != null ) { " +
" return window.frames[i].document.getElementById('tinymce').innerHTML; " +
" } } } )() ";

Here is my runScript method:

public String runScript(String javasript){
JavascriptExecutor js = (JavascriptExecutor) driver;
return (String) js.executeScript("return " + javascript);
}

This is the basic syntax:
( function x() { //do something & return value } )()

To Use with an argument:
( function(x) { //do something & return value } )(arg);


Learnings in Webdriver using C#.Net

Webdriver Tips and Techniques

The Automation Tester

My experiance with test automation

Learn WebDriver

This WordPress.com site is the cat’s pajamas

Assert Selenium

Selenium Automation in a Right Way