NAME
WWW::Mechanize - Handy web browsing in a Perl object
VERSION
Version 0.69_01
$Header: /cvsroot/www-mechanize/www-mechanize/lib/WWW/Mechanize.pm,v 1.89 2003/11/26 05:15:37 petdance Exp $
SYNOPSIS
WWW::Mechanize
, or Mech for short, helps 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. Mech also stores a history of the URLs you've visited, which can be queried and revisited.
use WWW::Mechanize;
my $a = WWW::Mechanize->new();
$a->get( $url );
$a->follow_link( n => 3 );
$a->follow_link( text_regex => qr/download this/i );
$a->follow_link( url => 'http://host.com/index.html' );
$a->submit_form(
form_number => 3,
fields => {
username => 'yourname',
password => 'dummy',
}
);
$a->submit_form(
form_name => 'search',
fields => { query => 'pot of gold', },
button => 'Search Now'
);
Mech is well suited for use in testing web applications. If you use one of the Test::*, like Test::HTML::Lint modules, you can check the fetched content and use that as input to a test call.
use Test::More;
like( $a->content(), qr/$expected/, "Got expected content" );
Each page fetch stores its URL in a history stack which you can traverse.
$a->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.
$a->follow( $link );
$a->find_link( n => $number );
$a->form_number( $number );
$a->form_name( $name );
$a->field( $name, $value );
$a->set_fields( %field_values );
$a->click( $button );
WWW::Mechanize is a proper subclass of LWP::UserAgent and you can also use any of LWP::UserAgent's methods.
$a->add_header($name => $value);
IMPORTANT LINKS
http://search.cpan.org/dist/WWW-Mechanize/
The CPAN documentation page for Mechanize.
http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Mechanize
The RT queue for bugs & enhancements in Mechanize. Click the "Report bug" link if your bug isn't already reported.
OTHER DOCUMENTATION
Spidering Hacks, by Kevin Hemenway and Tara Calishain
Spidering Hacks from O'Reilly (http://www.oreilly.com/catalog/spiderhks/) is a great book for anyone wanting to know more about screen-scraping and spidering.
There are three Mech-specific hacks by Andy Lester:
- 21 WWW::Mechanize 101
- 36 Downloading Images from Webshots
- 44 Archiving Yahoo! Groups Messages with WWW::Yahoo::Groups
and two Mech hacks from Chris Elthek:
Online resources
WWW::Mechanize Development mailing list
Hosted at Sourceforge, this is where the contributors to Mech discuss things. http://sourceforge.net/mail/?group_id=83309
LWP mailing list
The LWP mailing list is at http://lists.perl.org/showlist.cgi?name=libwww, and is more user-oriented and well-populated than the WWW::Mechanize Development list. This is a good list for Mech users, since LWP is the basis for Mech.
-
A random array of examples submitted by users, included with the Mechanize distribution.
http://www.perl.com/pub/a/2003/01/22/mechanize.html
Chris Ball's article about using WWW::Mechanize for scraping TV listings.
http://www.stonehenge.com/merlyn/LinuxMag/col47.html
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.http://www.perladvent.org/2002/16th/
WWW::Mechanize on the Perl Advent Calendar, by Mark Fowler.
Constructor and startup
new()
Creates and returns a new WWW::Mechanize object, hereafter referred to as the 'agent'.
my $a = 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 $a = 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 $a = 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. Default is off.
onwarn => \&func()
Reference to a
warn
-compatible function, such asCarp::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 thequiet
method to control that behavior.If this value is not passed, Mech uses
Carp::carp
if Carp is installed, orCORE::warn
if not.onerror => \&func()
Reference to a
die
-compatible function, such asCarp::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, orCORE::die
if not.quiet => [0|1]
Don't complain on warnings. Setting
quiet => 1
is the same as calling$agent->quiet(1)
. Default is off.
$a->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,
$a->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()
.
known_agent_aliases()
Returns a list of all the agent aliases that Mech knows about.
Page-fetching methods
$a->get($url)
Given a URL/URI, fetches it. Returns an HTTP::Response object. $url can be a well-formed URL string, or a URI 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.
get()
is a well-behaved overloaded version of the method in LWP::UserAgent. This lets you do things like
$mech->get( $url, ":content_file"=>$tempfile );
and you can rest assured that the parms will get filtered down appropriately.
$a->reload()
Acts like the reload button in a browser: Reperforms the current request.
Returns the HTTP::Response object from the reload, or undef
if there's no current request.
$a->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?)
Link-following methods
$a->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"
$a->follow_link( text => "download", n => 3 );
first link where the URL has "download" in it, regardless of case:
$a->follow_link( url_regex => qr/download/i );
or
$a->follow_link( url_regex => qr/(?i:download)/ );
3rd link on the page
$a->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 $a->follow()
which should not be used in future development.
Form field filling methods
$a->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. Emits a warning and returns undef if there is no such form. Forms are indexed from 1, so the first form is number 1, not zero.
$a->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. Also returns the form itself, or undef if it's not found.
Note that this functionality requires libwww-perl 5.69 or higher.
$a->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.
$a->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
$a->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).
$a->tick( $name, $value [, $set] )
'Ticks' the first checkbox that has both the name and value assoicated 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.
$a->untick($name, $value)
Causes the checkbox to be unticked. Shorthand for tick($name,$value,undef)
Form submission methods
$a->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) coordinates of the click.
If there is only one button on the form, $a->click()
with no arguments simply clicks that one button.
Returns an HTTP::Response object.
$a->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.
$a->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()
). If this parm is not specified, the currently-selected form is used.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.
Status methods
$a->success()
Returns a boolean telling whether the last request was successful. If there hasn't been an operation yet, returns false.
This is a convenience function that wraps $a->res->is_success
.
$a->uri()
Returns the current URI.
$a->response()
or $a->res()
Return the current response as an HTTP::Response object.
Synonym for $a->response()
$a->status()
Returns the HTTP status code of the response.
$a->ct()
Returns the content type of the response.
$a->base()
Returns the base URI for the current response
$a->content()
Returns the content for the response
$a->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.
$a->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.
$a->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.
$a->is_html()
Returns true/false on whether our content is HTML, according to the HTTP headers.
$a->title()
Returns the contents of the <TITLE>
tag, as parsed by HTML::HeadParser. Returns undef if the content is not HTML.
Content-handling methods
$a->find_link()
This method 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
andtext_regex => 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$a->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$a->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
andurl_regex => regex
Matches the URL of the link against string or regex, as appropriate.
name => string
andname_regex => regex
Matches the name of the link against string or regex, as appropriate.
tag => string
andtag_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:$a->find_link( tag_regex => qr/^(a|img)$/;
n => number
Matches against the nth link.
The
n
parms can be combined with the other parms above 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.
Note that you can specify multiple text or URL parameters, which will be ANDed together. For example, to find the first link with text of "News" and with "cnn.com" in the URL, use:
$a->find_link( text => "News", url_regex => qr/cnn\.com/ );
$a->find_link()
: link format
The return value is a reference to an array containing a WWW::Mechanize::Link object for every link in $self->content
.
The links come from the following:
$a->find_all_links( ... )
Returns all the links on the current page that match the criteria. The method for specifying link criteria is the same as in find_link()
. Each of the links returned is a WWW::Mechanize::Link object.
In list context, find_all_links()
returns a list of the links. Otherwise, it returns a reference to the list of links.
find_all_links()
with no parameters returns all links in the page.
Miscellaneous methods
$a->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.
$a->quiet(true/false)
Allows you to suppress warnings to the screen.
$a->quiet(0); # turns on warnings (the default)
$a->quiet(1); # turns off warnings
$a->quiet(); # returns the current quietness status
Overridden LWP::UserAgent methods
$a->redirect_ok()
An overloaded version of redirect_ok()
in LWP::UserAgent. This method is used to determine whether a redirection in the request should be followed.
$a->request( $request [, $arg [, $size]])
Overloaded version of request()
in LWP::UserAgent. Performs the actual request. Normally, if you're using WWW::Mechanize, it'd because you don't want to deal with this level of stuff anyway.
Note that $request
will be modified.
Returns an HTTP::Response object.
$a->_parse_html()
An internal method that initializes forms and links given a HTML document. If you need to override this in your subclass, or call it multiple times, go ahead.
_make_request()
Convenience method to make it easier for subclasses like WWW::Mechanize::Cached to intercept the request.
Deprecated methods
This methods have been replaced by more flexible and precise methods. Please use them instead.
$a->follow($string|$num)
DEPRECATED in favor of follow_link()
, which provides more flexibility.
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.
$a->form($number|$name)
DEPRECATED in favor of form_name()
or form_number()
.
Selects a form by number or name, depending on if it gets passed an all-numeric string or not. This means that if you have a form name that's all digits, this method will not do the right thing.
Internal-only methods
These methods are only used internally. You probably don't need to know about them.
$a->_reset_page()
Resets the internal fields that track page parsed stuff.
$a->_extract_links()
Extracts links from the content of a webpage, and populates the {links}
property with WWW::Mechanize::Link objects.
$a->_push_page_stack()
and $a->_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 $a object.
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.
Other modules that use Mechanize
Here's a list of modules that use or subclass Mechanize. Let me know of any others:
Requests & Bugs
Please report any requests, suggestions or (gasp!) bugs via the excellent RT bug-tracking 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.
http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Mechanize is the RT queue for Mechanize. Please check to see if your bug has already been reported.
Author
Copyright 2003 Andy Lester <andy@petdance.com>
Released under the Artistic License. Based on Kirrily Robert's excellent WWW::Automate package.
1 POD Error
The following errors were encountered while parsing the POD:
- Around line 112:
Expected text after =item, not a bullet