The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

WWW::Mechanize - automate interaction with websites

SYNOPSIS

WWW::Mechanize is intended to help you automate interaction with a website. It supports performing a sequence of page fetches including following links and submitting forms. Each fetched page is parsed and its links and forms are extracted. A link or a form can be selected, form fields can be filled and the next page can be fetched. A history of fetched pages is also stored and can be traversed.

    use WWW::Mechanize;
    my $agent = WWW::Mechanize->new();

    $agent->get($url);

    $agent->follow_link( 'n' => 3 );
    $agent->follow_link( 'link_regex' => qr/download this/i );
    $agent->follow_link( 'url' => 'http://host.com/index.html' );

    $agent->submit_form(
        'form_number' => 3,
        'fields'      => {
                            'user_name'  => 'yourname',
                            'password'   => 'dummy'
                        }
    );

    $agent->submit_form(
        'form_name' => 'search',
        'fields'    => {
                        'query'  => 'pot of gold',
                        },
        'button'    => 'Search Now'
    );

WWW::Mechanize is well suited for use in testing web applications. If you use one of the Test::* modules, you can check the fetched content and use that as input to a test call.

    use Test::More;
    like( $agent->content(), qr/$expected/, "Got expected content" );

Each page fetch stores its URL in a history stack which you can traverse.

    $agent->back();

If you want finer control over over your page fetching, you can use these methods. follow_link and submit_form are just high level wrappers around them.

    $agent->follow($link);
    $agent->find_link(n => $number);
    $agent->form_number($number);
    $agent->form_name($name);
    $agent->field($name, $value);
    $agent->set_fields( %field_values );
    $agent->click($button);

WWW::Mechanize is a subclass of LWP::UserAgent and you can also use any of its methods.

    $agent->add_header($name => $value);

OTHER DOCUMENTATION

VERSION

Version 0.41

    $Header: /home/cvs/www-mechanize/lib/WWW/Mechanize.pm,v 1.75 2003/05/23 04:23:34 alester Exp $

METHODS

new()

Creates and returns a new WWW::Mechanize object, hereafter referred to as the 'agent'.

    my $agent = WWW::Mechanize->new()

The constructor for WWW::Mechanize overrides two of the parms to the LWP::UserAgent constructor:

    agent => "WWW-Mechanize/#.##"
    cookie_jar => {}    # an empty, memory-only HTTP::Cookies object

You can override these overrides by passing parms to the constructor, as in:

    my $agent = WWW::Mechanize->new( agent=>"wonderbot 1.01" );

If you want none of the overhead of a cookie jar, or don't want your bot accepting cookies, you have to explicitly disallow it, like so:

    my $agent = WWW::Mechanize->new( cookie_jar => undef );

$agent->get($url)

Given a URL/URI, fetches it. Returns an HTTP::Response object.

The results are stored internally in the agent object, but you don't know that. Just use the accessors listed below. Poking at the internals is deprecated and subject to change in the future.

$agent->uri()

Returns the current URI.

$agent->req()

Returns the current request as an HTTP::Request object.

$agent->res()

Returns the current response as an HTTP::Response object.

$agent->status()

Returns the HTTP status code of the response.

$agent->ct()

Returns the content type of the response.

$agent->base()

Returns the base URI for the current response

$agent->content()

Returns the content for the response

$agent->forms()

When called in a list context, returns a list of the forms found in the last fetched page. In a scalar context, returns a reference to an array with those forms. The forms returned are all HTML::Form objects.

$agent->current_form()

Returns the current form as an HTML::Form object. I'd call this form() except that form() already exists and sets the current_form.

$agent->links()

When called in a list context, returns a list of the links found in the last fetched page. In a scalar context it returns a reference to an array with those links. The links returned are all references to two element arrays which contain the URL and the text for each link.

$agent->is_html()

Returns true/false on whether our content is HTML, according to the HTTP headers.

$agent->title()

Returns the contents of the <TITLE> tag, as parsed by HTML::HeadParser. Returns undef if the content is not HTML.

Action methods

$agent->follow($string|$num)

Follow a link. If you provide a string, the first link whose text matches that string will be followed. If you provide a number, it will be the $numth link on the page. Note that the links are 0-based.

Returns true if the link was found on the page or undef otherwise.

$agent->find_link()

This method finds a link in the currently fetched page. It returns a reference to a two element array which has the link URL and link text, respectively. If it fails to find a link it returns undef. You can take the URL part and pass it to the get method. The follow_link method is recommended as it calls this method and also does the get for you.

Note that <FRAME SRC="..." tags are parsed out of the the HTML and treated as links so this method works with them.

You can select which link to find by passing in one of these key/value pairs:

text => string

Matches the text of the link against string, which must be an exact match.

To select a link with text that is exactly "download", use

    $agent->find_link( text => "download" );
text_regex => regex

Matches the text of the link against regex.

To select a link with text that has "download" anywhere in it, regardless of case, use

    $agent->find_link( text_regex => qr/download/i );
url => string

Matches the URL of the link against string, which must be an exact match. This is similar to the text parm.

url_regex => regex

Matches the URL of the link against regex. This is similar to the text_regex parm.

n => number

Matches against the nth link.

The n parms can be combined with the text* or url* parms as a numeric modifier. For example, text => "download", n => 3 finds the 3rd link which has the exact text "download".

If n is not specified, it defaults to 1. Therefore, if you don't specify any parms, this method defaults to finding the first link on the page.

$agent->follow_link()

Follows a specified link on the page. You specify the match to be found using the same parms that find_link() uses.

Here some examples:

  • 3rd link called "download"

        $agent->follow_link( text => "download", n => 3 );
  • first link where the URL has "download" in it, regardless of case:

        $agent->follow_link( url_regex => qr/download/i );

    or

        $agent->follow_link( url_regex => "(?i:download)" );
  • 3rd link on the page

        $agent->follow_link( n => 3 );

Returns the result of the GET method (an HTTP::Response object) if a link was found. If the page has no links, or the specified link couldn't be found, returns undef.

This method is meant to replace $agent->follow() which should not be used in future development.

$agent->submit_form()

This method lets you select a form from the previously fetched page, fill in its fields, and submit it. It combines the form_number/form_name, set_fields and click methods into one higher level call. Its arguments are a list of key/value pairs, all of which are optional.

  • form_number => n

    Selects the nth form (calls form_number())

  • form_name => name

    Selects the form named name (calls form_name())

  • fields => fields

    Sets the field values from the fields hashref (calls set_fields())

  • button => button

    Clicks on button button (calls click())

  • x => x, y => y

    Sets the x or y values for click()

If no form is selected, the first form found is used.

If button is not passed, then the submit() method is used instead.

Returns an HTTP::Response object.

$agent->quiet(true/false)

Allows you to suppress warnings to the screen.

    $agent->quiet(0); # turns on warnings (the default)
    $agent->quiet(1); # turns off warnings
    $agent->quiet();  # returns the current quietness status

$agent->form($number|$name)

Selects a form by number or name, depending on if it gets passed an all-numeric string or not. If you have a form with a name that is all digits, you'll need to call $agent->form_name explicitly.

This method is deprecated. Use form_name or form_number instead.

$agent->form_number($number)

Selects the Nth form on the page as the target for subsequent calls to field() and click(). Emits a warning and returns false if there is no such form. Forms are indexed from 1, that is to say, the first form is number 1 (not zero).

$agent->form_name($name)

Selects a form by name. If there is more than one form on the page with that name, then the first one is used, and a warning is generated.

Note that this functionality requires libwww-perl 5.69 or higher.

$agent->field($name, $value, $number)

Given the name of a field, set its value to the value specified. This applies to the current form (as set by the form() method or defaulting to the first form on the page).

The optional $number parameter is used to distinguish between two fields with the same name. The fields are numbered from 1.

$agent->set_fields( $name => $value ... )

This method sets multiple fields of a form. It takes a list of field name and value pairs. If there is more than one field with the same name, the first one found is set. If you want to select which of the duplicate field to set, use a value which is an anonymous array which has the field value and its number as the 2 elements.

        # set the second foo field
        $agent->set_fields( $name => [ 'foo', 2 ] ) ;

The fields are numbered from 1.

This applies to the current form (as set by the form() method or defaulting to the first form on the page).

$agent->click($button, $x, $y)

Has the effect of clicking a button on a form. The first argument is the name of the button to be clicked. The second and third arguments (optional) allow you to specify the (x,y) cooridinates of the click.

If there is only one button on the form, $agent->click() with no arguments simply clicks that one button.

Returns an HTTP::Response object.

$agent->submit()

Submits the page, without specifying a button to click. Actually, no button is clicked at all.

This used to be a synonym for $a->click("submit"), but is no longer so.

$agent->back()

The equivalent of hitting the "back" button in a browser. Returns to the previous page. Won't go back past the first page. (Really, what would it do if it could?)

$agent->add_header(name => $value)

Sets a header for the WWW::Mechanize agent to use every time it gets a webpage. This is NOT stored in the agent object (because if it were, it would disappear if you went back() past where you'd set it) but in the hash variable %WWW::Mechanize::headers, which is a hash of all headers to be set. You can manipulate this directly if you want to; the add_header() method is just provided as a convenience function for the most common case of adding a header.

extract_links()

Extracts HREF links from the content of a webpage.

The return value is a reference to an array containing an array reference for every <A> and <FRAME> tag in $self->{content}.

The array elements for the <A> tag are:

[0]: contents of the href attribute
[1]: text enclosed by the <A> tag
[2]: the contents of the name attribute

The array elements for the <FRAME> tag are:

[0]: contents of the src attribute
[1]: text enclosed by the <FRAME> tag
[2]: contents of the name attribute

INTERNAL METHODS

These methods are only used internally. You probably don't need to know about them.

_push_page_stack() / _pop_page_stack()

The agent keeps a stack of visited pages, which it can pop when it needs to go BACK and so on.

The current page needs to be pushed onto the stack before we get a new page, and the stack needs to be popped when BACK occurs.

Neither of these take any arguments, they just operate on the $agent object.

_do_request()

Performs a request on the $self->{req} request object, and sets a bunch of attributes on $self.

Returns an HTTP::Response object.

FAQ

Can I do [such-and-such] with WWW::Mechanize?

If it's possible with LWP::UserAgent, then yes. WWW::Mechanize is a subclass of LWP::UserAgent, so all the wondrous magic of that class is inherited.

How do I use WWW::Mechanize through a proxy server?

See the docs in LWP::UserAgent on how to use the proxy. Short version:

    $agent->proxy(['http', 'ftp'], 'http://proxy.example.com:8000/');

or get the specs from the environment:

    $agent->env_proxy();

    # Environment set like so:
    gopher_proxy=http://proxy.my.place/
    wais_proxy=http://proxy.my.place/
    no_proxy="localhost,my.domain"
    export gopher_proxy wais_proxy no_proxy

SEE ALSO

See also WWW::Mechanize::Examples for sample code. WWW::Mechanize::FormFiller and WWW::Mechanize::Shell are add-ons that turn Mechanize into more of a scripting tool.

REQUESTS & BUGS

Please report any requests, suggestions or (gasp!) bugs via the system at http://rt.cpan.org/, or email to bug-WWW-Mechanize@rt.cpan.org. This makes it much easier for me to track things.

AUTHOR

Copyright 2002 Andy Lester <andy@petdance.com>

Released under the Artistic License. Based on Kirrily Robert's excellent WWW::Automate package.