Skip to content

Page Transformers

gavinbunney edited this page Feb 15, 2011 · 1 revision

Page Transformers

It's occasionally the case that you'll come across a page that Madcow/HTMLUnit is unable to parse without an error. You can create a page transformer to handle the problem. Page transformers allow Madcow to make any necessary changes to an html page before Madcow attempts to deal with it.

Create a Page Transformer Class

Create a new groovy class that implements the interface au.com.ts4impact.madcow.pagetransformers.PageTransformer

Implement transformPage method

Implement the method from the interface - public Page transformPage(Page). In this method, you can do any necessary transformations to the HTML page before it is processed. Simply return the modified page.

Here's an example:

public class BreakAltaVista implements PageTransformer {

  private static final Logger LOG = Logger.getLogger(BreakAltaVista.class);
  
  private static final String FIND_BUTTON_XPATH = "//input[@value='FIND']"

  public Page transformPage(Page page) {
    if (page instanceof HtmlPage) {
      HtmlInput altaVistaFindButton = ((HtmlPage) page).getFirstByXPath(FIND_BUTTON_XPATH)
      if (altaVistaFindButton) {
        LOG.debug "The AltaVista search button was found, and will be 'fixed' to redirect to www.google.com."
        altaVistaFindButton.setAttribute("onClick", "parent.location='http://www.google.com'")
      }
    }
    return page
  }
}

Register Page Transformer

In order to get the transformer to be applied to any pages that are processed, add the full class name (including the package) to /conf/madcow.pagetransformers.properties.

Clone this wiki locally