3.1: Using Java

Create the Script

The Java class we'll be writing will simply substitute for the Initialize scraping session script we wrote previously. That is, our Java class will invoke our scraping session remotely and pass in a value for the TEXT_TO_SUBMIT session variable. Create a new Java class on your computer, and paste the following code into it:

import com.screenscraper.scraper.*;

public class HelloWorldRemoteScrapingSession
{
    /**
     * The entry point.
     */

    public static void main( String args[] )
    {
        try
        {
            // Create a remoteSession to communicate with the server.
            RemoteScrapingSession remoteSession = new RemoteScrapingSession( "Hello World" );

            // Put the text to be submitted in the form into a session variable so we can reference it later.
            remoteSession.setVariable( "TEXT_TO_SUBMIT", "Hi everybody!" );

            // Tell the session to scrape.
            remoteSession.scrape();

            // Output the text that was scraped:
            System.out.println( "Scraped text: " + remoteSession.getVariable( "FORM_SUBMITTED_TEXT" ) );

            // Very important! Be sure to disconnect from the server.
            remoteSession.disconnect();
        }
        catch( Exception e )
        {
            System.err.println( e.getMessage() );
        }
    }
}

Script Explanation

For the most part this Java code is virtually identical to our script. The one notable difference is that we need to explicitly disconnect from the server so that it knows we're done.

Running the Script

OK, we're ready to give our Java class a try. After you've successfully compiled the class (remember to include the "screen-scraper.jar" file in your classpath), start screen-scraper running as a server. If you've succeeded in starting up the server go ahead and run the Java class from a command prompt or console. After a short pause you should see the "Hi everybody!" message output.