NAME

VERSION

SYNOPSIS

WWW::Mechanize, or Mech for short, is a Perl module for stateful programmatic web browsing, used for automating interaction with websites.

Features include:

All HTTP methods

High-level hyperlink and HTML form support, without having to parse HTML yourself

SSL support

Automatic cookies

Custom HTTP headers

Automatic handling of redirections

Proxies

HTTP authentication

Mech 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. Mech also stores a history of the URLs you've visited, which can be queried and revisited.

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

my $mech = 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 $mech = WWW::Mechanize->new( cookie_jar => undef );

Here are the parms that WWW::Mechanize recognizes. These do not include parms that LWP::UserAgent recognizes.

autocheck => [0|1]

Checks each request made to see if it was successful. This saves you the trouble of manually checking yourself. Any errors found are errors, not warnings.

The default value is ON, unless it's being subclassed, in which case it is OFF. This means that standalone WWW::Mechanizeinstances have autocheck turned on, which is protective for the vast majority of Mech users who don't bother checking the return value of get() and post() and can't figure why their code fails. However, if WWW::Mechanize is subclassed, such as for Test::WWW::Mechanize or Test::WWW::Mechanize::Catalyst, this may not be an appropriate default, so it's off.

This needs to be explicitly turned off if you're using Crypt::SSLeay to access a https site via a proxy server. Note: you still need to set your HTTPS_PROXY environment variable as appropriate.

onwarn => \&func

Reference to a warn-compatible function, such as Carp::carp, that is called when a warning needs to be shown.

If this is set to undef, no warnings will ever be shown. However, it's probably better to use the quiet method to control that behavior.

If this value is not passed, Mech uses Carp::carp if Carp is installed, or CORE::warn if not.

onerror => \&func

Reference to a die-compatible function, such as Carp::croak, that is called when there's a fatal error.

If this is set to undef, no errors will ever be shown.

If this value is not passed, Mech uses Carp::croak if Carp is installed, or CORE::die if not.

quiet => [0|1]

Don't complain on warnings. Setting quiet => 1 is the same as calling $mech->quiet(1). Default is off.

stack_depth => $value

Sets the depth of the page stack that keeps track of all the downloaded pages. Default is effectively infinite stack size. If the stack is eating up your memory, then set this to a smaller number, say 5 or 10. Setting this to zero means Mech will keep no history.

To support forms, WWW::Mechanize's constructor pushes POST on to the agent's requests_redirectable list (see also LWP::UserAgent.)

$mech->agent_alias( $alias )

Sets the user agent string to the expanded version from a table of actual user strings. $alias can be one of the following:

Windows IE 6

Windows Mozilla

Mac Safari

Mac Mozilla

Linux Mozilla

Linux Konqueror

then it will be replaced with a more interesting one. For instance,

$mech->agent_alias( 'Windows IE 6' );

sets your User-Agent to

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

The list of valid aliases can be returned from known_agent_aliases(). The current list is:

$mech->response() / $mech->res()

$mech->status()

Returns the HTTP status code of the response. This is a 3-digit number like 200 for OK, 404 for not found, and so on.

$mech->ct() / $mech->content_type()

Returns the content type of the response.

$mech->base()

Returns the base URI for the current response

$mech->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.

$mech->current_form()

$mech->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. Each link is a WWW::Mechanize::Link object.

$mech->is_html()

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

$mech->title()

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

CONTENT-HANDLING METHODS

$mech->content(...)

Returns the content that the mech uses internally for the last page fetched. Ordinarily this is the same as $mech->response()->content(), but this may differ for HTML documents if "update_html" is overloaded (in which case the value passed to the base-class implementation of same will be returned), and/or extra named arguments are passed to content():

$mech->content( format => 'text' )

Returns a text-only version of the page, with all HTML markup stripped. This feature requires HTML::TreeBuilder to be installed, or a fatal error will be thrown.

$mech->content( base_href => [$base_href|undef] )

Returns the HTML document, modified to contain a <base href="$base_href"> mark-up in the header. $base_href is $mech->base() if not specified. This is handy to pass the HTML to e.g. HTML::Display.

Passing arguments to content() if the current document is not HTML has no effect now (i.e. the return value is the same as $self->response()->content(). This may change in the future, but will likely be backwards-compatible when it does.

$mech->text()

Returns the text of the current HTML content. If the content isn't HTML, $mech will die.

The text is extracted by parsing the content, and then the extracted text is cached, so don't worry about performance of calling this repeatedly.

LINK METHODS

$mech->links()

Lists all the links on the current page. Each link is a WWW::Mechanize::Link object. In list context, returns a list of all links. In scalar context, returns an array reference of all links.

$mech->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"

$mech->follow_link( text => 'download', n => 3 );

first link where the URL has "download" in it, regardless of case:

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

or

$mech->follow_link( url_regex => qr/(?i:download)/ );

3rd link on the page

$mech->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.

$mech->find_link( ... )

Finds a link in the currently fetched page. It returns a WWW::Mechanize::Link object which describes the link. (You'll probably be most interested in the url() property.) If it fails to find a link it returns undef.

You can take the URL part and pass it to the get() method. If that's your plan, you might as well use the follow_link() method directly, since it does the get() for you automatically.

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 or more of these key/value pairs:

text => 'string', and text_regex => qr/regex/,

text 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

$mech->find_link( text => 'download' );

text_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

$mech->find_link( text_regex => qr/download/i );

Note that the text extracted from the page's links are trimmed. For example, <a> foo </a> is stored as 'foo', and searching for leading or trailing spaces will fail.

url => 'string', and url_regex => qr/regex/,

Matches the URL of the link against string or regex, as appropriate. The URL may be a relative URL, like foo/bar.html, depending on how it's coded on the page.

url_abs => string and url_abs_regex => regex

Matches the absolute URL of the link against string or regex, as appropriate. The URL will be an absolute URL, even if it's relative in the page.

name => string and name_regex => regex

Matches the name of the link against string or regex, as appropriate.

id => string and id_regex => regex

Matches the attribute 'id' of the link against string or regex, as appropriate.

class => string and class_regex => regex

Matches the attribute 'class' of the link against string or regex, as appropriate.

tag => string and tag_regex => regex

Matches the tag that the link came from against string or regex, as appropriate. The tag_regex is probably most useful to check for more than one tag, as in:

$mech->find_all_submits( ... criteria ... )

find_all_submits() does the same thing as find_all_inputs() except that it only returns controls that are submit controls, ignoring other types of input controls like text and checkboxes.

IMAGE METHODS

$mech->images

Lists all the images on the current page. Each image is a WWW::Mechanize::Image object. In list context, returns a list of all images. In scalar context, returns an array reference of all images.

$mech->find_image()

Finds an image in the current page. It returns a WWW::Mechanize::Image object which describes the image. If it fails to find an image it returns undef.

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

alt => 'string' and alt_regex => qr/regex/,

alt matches the ALT attribute of the image against string, which must be an exact match. To select a image with an ALT tag that is exactly "download", use

$mech->find_image( alt => 'download' );

alt_regex matches the ALT attribute of the image against a regular expression. To select an image with an ALT attribute that has "download" anywhere in it, regardless of case, use

$mech->find_image( alt_regex => qr/download/i );

url => 'string', and url_regex => qr/regex/,

Matches the URL of the image against string or regex, as appropriate. The URL may be a relative URL, like foo/bar.html, depending on how it's coded on the page.

url_abs => string and url_abs_regex => regex

Matches the absolute URL of the image against string or regex, as appropriate. The URL will be an absolute URL, even if it's relative in the page.

tag => string and tag_regex => regex

Matches the tag that the image came from against string or regex, as appropriate. The tag_regex is probably most useful to check for more than one tag, as in:

$mech->find_image( tag_regex => qr/^(img|input)$/ );

The tags supported are <img> and <input>.

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

Note that you can specify multiple ALT or URL parameters, which will be ANDed together. For example, to find the first image with ALT text of "News" and with "cnn.com" in the URL, use:

$mech->find_image( image => 'News', url_regex => qr/cnn\.com/ );

The return value is a reference to an array containing a WWW::Mechanize::Image object for every image in $self->content.

$mech->find_all_images( ... )

Returns all the images on the current page that match the criteria. The method for specifying image criteria is the same as in "find_image()". Each of the images returned is a WWW::Mechanize::Image object.

In list context, find_all_images() returns a list of the images. Otherwise, it returns a reference to the list of images.

find_all_images() with no parameters returns all images in the page.

FORM METHODS

These methods let you work with the forms on a page. The idea is to choose a form that you'll later work with using the field methods below.

$mech->forms

Lists all the forms on the current page. Each form is an HTML::Form object. In list context, returns a list of all forms. In scalar context, returns an array reference of all forms.

$mech->form_number($number)

Selects the numberth form on the page as the target for subsequent calls to "field()" and "click()". Also returns the form that was selected.

If it is found, the form is returned as an HTML::Form object and set internally for later use with Mech's form methods such as "field()" and "click()".

Emits a warning and returns undef if no form is found.

The first form is number 1, not zero.

$mech->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.

If it is found, the form is returned as an HTML::Form object and set internally for later use with Mech's form methods such as "field()" and "click()".

Returns undef if no form is found.

$mech->form_id( $name )

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

If it is found, the form is returned as an HTML::Form object and set internally for later use with Mech's form methods such as "field()" and "click()".

Returns undef if no form is found.

$mech->form_with_fields( @fields )

Selects a form by passing in a list of field names it must contain. If there is more than one form on the page with that matches, then the first one is used, and a warning is generated.

If it is found, the form is returned as an HTML::Form object and set internally for later used with Mech's form methods such as "field()" and "click()".

Returns undef if no form is found.

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

FIELD METHODS

These methods allow you to set the values of fields in a given form.

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

$mech->field( $name, \@values, $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_name()" or "form_number()" 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.

$mech->select($name, $value)

$mech->select($name, \@values)

Given the name of a select field, set its value to the value specified. If the field is not <select multiple> and the $value is an array, only the first value will be set. [Note: the documentation previously claimed that only the last value would be set, but this was incorrect.] Passing $value as a hash with an n key selects an item by number (e.g. {n => 3} or {n => [2,4]}). The numbering starts at 1. This applies to the current form.

If you have a field with <select multiple> and you pass a single $value, then $value will be added to the list of fields selected, without clearing the others. However, if you pass an array reference, then all previously selected values will be cleared.

Returns true on successfully setting the value. On failure, returns false and calls $self>warn() with an error message.

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

This method sets multiple fields of the current 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.

$mech->set_visible( @criteria )

This method sets fields of the current form without having to know their names. So if you have a login screen that wants a username and password, you do not have to fetch the form and inspect the source (or use the mech-dump utility, installed with WWW::Mechanize) to see what the field names are; you can just say

$mech->set_visible( $username, $password );

and the first and second fields will be set accordingly. The method is called set_visible because it acts only on visible fields; hidden form inputs are not considered. The order of the fields is the order in which they appear in the HTML source which is nearly always the order anyone viewing the page would think they are in, but some creative work with tables could change that; caveat user.

Each element in @criteria is either a field value or a field specifier. A field value is a scalar. A field specifier allows you to specify the type of input field you want to set and is denoted with an arrayref containing two elements. So you could specify the first radio button with

$mech->set_visible( [ radio => 'KCRW' ] );

Field values and specifiers can be intermixed, hence

$mech->set_visible( 'fred', 'secret', [ option => 'Checking' ] );

would set the first two fields to "fred" and "secret", and the nextOPTION menu field to "Checking".

$mech->tick( $name, $value [, $set] )

"Ticks" the first checkbox that has both the name and value associated with it on the current form. Dies if there is no named check box for that value. Passing in a false value as the third optional argument will cause the checkbox to be unticked.

$mech->untick($name, $value)

Causes the checkbox to be unticked. Shorthand for tick($name,$value,undef)

$mech->value( $name [, $number] )

Given the name of a field, return its value. This applies to the current form.

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

If the field is of type file (file upload field), the value is always cleared to prevent remote sites from downloading your local files. To upload a file, specify its file name explicitly.

$mech->click( $button [, $x, $y] )

Has the effect of clicking a button on the current 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) coordinates of the click.

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

$mech->click_button( ... )

Has the effect of clicking a button on the current form by specifying its name, value, or index. Its arguments are a list of key/value pairs. Only one of name, number, input or value must be specified in the keys.

$mech->submit()

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

$mech->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.

fields => \%fields

Specifies the fields to be filled in the current form.

with_fields => \%fields

Probably all you need for the common case. It combines a smart form selector and data setting in one operation. It selects the first form that contains all fields mentioned in \%fields. This is nice because you don't need to know the name or number of the form to do this.

MISCELLANEOUS METHODS

$mech->add_header( name => $value [, name => $value... ] )

Sets HTTP headers for the agent to add or remove from the HTTP request.

$mech->add_header( Encoding => 'text/klingon' );

If a value is undef, then that header will be removed from any future requests. For example, to never send a Referer header:

$mech->add_header( Referer => undef );

If you want to delete a header, use delete_header.

Returns the number of name/value pairs added.

NOTE: This method was very different in WWW::Mechanize before 1.00. Back then, the headers were stored in a package hash, not as a member of the object instance. Calling add_header() would modify the headers for every WWW::Mechanize object, even after your object no longer existed.

$mech->delete_header( name [, name ... ] )

Removes HTTP headers from the agent's list of special headers. For instance, you might need to do something like:

This method is also used internally by the mech itself to update its own HTML content when loading a page. This means that if you would like to systematically perform the above HTML substitution, you would overload update_html in a subclass thusly:

If you do this, then the mech will use the tidied-up HTML instead of the original both when parsing for its own needs, and for returning to you through "content".

Overloading this method is also the recommended way of implementing extra validation steps (e.g. link checkers) for every HTML page received. "warn" and "die" would then come in handy to signal validation errors.

$mech->credentials( $username, $password )

Provide credentials to be used for HTTP Basic authentication for all sites and realms until further notice.

The four argument form described in LWP::UserAgent is still supported.

$mech->get_basic_credentials( $realm, $uri, $isproxy )

Returns the credentials for the realm and URI.

$mech->clear_credentials()

Remove any credentials set up with credentials().

INHERITED UNCHANGED LWP::UserAgent METHODS

As a sublass of LWP::UserAgent, WWW::Mechanize inherits all of LWP::UserAgent's methods. Many of which are overridden or extended. The following methods are inherited unchanged. View the LWP::UserAgent documentation for their implementation descriptions.

This is not meant to be an inclusive list. LWP::UA may have added others.

ARTICLES ABOUT WWW::MECHANIZE

Leland Johnson's hack #84 in Google Hacks, 2nd Edition is an example of a production script that uses WWW::Mechanize and HTML::TableContentParser. It takes in keywords and returns the estimated price of these keywords on Google's AdWords program.

Randal Schwartz's article on scraping Yahoo News for images. It's already out of date: He manually walks the list of links hunting for matches, which wouldn't have been necessary if the find_link() method existed at press time.