lib/WWW/Mechanize.pm

filter: Statementstmt 79.8% 582 / 729 Branchbran 62.1% 251 / 404 Conditioncond 61.8% 115 / 186 MC/DCmcdc 41.5% 42 / 101 Subroutinesub 84.0% 79 / 94 Podpod 100% 64 / 64 totaltotal 71.8% 1133 / 1578 CC 294 SCAR 32.7
CC
294
Cov
72%
click_button
182.0
_match_any_image_parms
107.3
submit_form
71.6
CRAP 26.2
↑ Summary lib/WWW/Mechanize/Image.pm »
1 package WWW::Mechanize;
2  
3 =head1 NAME
4  
5 WWW::Mechanize - Handy web browsing in a Perl object
6  
7 =head1 VERSION
8  
9 Version 1.72_02
10  
11 =cut
12  
13 47 our $VERSION = '1.72_02';
14  
15 =head1 SYNOPSIS
16  
17 C<WWW::Mechanize>, or Mech for short, is a Perl module for stateful
18 programmatic web browsing, used for automating interaction with
19 websites.
20  
21 Features include:
22  
23 =over 4
24  
25 =item * All HTTP methods
26  
27 =item * High-level hyperlink and HTML form support, without having to parse HTML yourself
28  
29 =item * SSL support
30  
31 =item * Automatic cookies
32  
33 =item * Custom HTTP headers
34  
35 =item * Automatic handling of redirections
36  
37 =item * Proxies
38  
39 =item * HTTP authentication
40  
41 =back
42  
43 Mech supports performing a sequence of page fetches including
44 following links and submitting forms. Each fetched page is parsed
45 and its links and forms are extracted. A link or a form can be
46 selected, form fields can be filled and the next page can be fetched.
47 Mech also stores a history of the URLs you've visited, which can
48 be queried and revisited.
49  
50 use WWW::Mechanize;
51 my $mech = WWW::Mechanize->new();
52  
53 $mech->get( $url );
54  
55 $mech->follow_link( n => 3 );
56 $mech->follow_link( text_regex => qr/download this/i );
57 $mech->follow_link( url => 'http://host.com/index.html' );
58  
59 $mech->submit_form(
60 form_number => 3,
61 fields => {
62 username => 'mungo',
63 password => 'lost-and-alone',
64 }
65 );
66  
67 $mech->submit_form(
68 form_name => 'search',
69 fields => { query => 'pot of gold', },
70 button => 'Search Now'
71 );
72  
73  
74 Mech is well suited for use in testing web applications. If you use
75 one of the Test::*, like L<Test::HTML::Lint> modules, you can check the
76 fetched content and use that as input to a test call.
77  
78 use Test::More;
79 like( $mech->content(), qr/$expected/, "Got expected content" );
80  
81 Each page fetch stores its URL in a history stack which you can
82 traverse.
83  
84 $mech->back();
85  
86 If you want finer control over your page fetching, you can use
87 these methods. C<follow_link> and C<submit_form> are just high
88 level wrappers around them.
89  
90 $mech->find_link( n => $number );
91 $mech->form_number( $number );
92 $mech->form_name( $name );
93 $mech->field( $name, $value );
94 $mech->set_fields( %field_values );
95 $mech->set_visible( @criteria );
96 $mech->click( $button );
97  
98 L<WWW::Mechanize> is a proper subclass of L<LWP::UserAgent> and
99 you can also use any of L<LWP::UserAgent>'s methods.
100  
101 $mech->add_header($name => $value);
102  
103 Please note that Mech does NOT support JavaScript, you need additional software
104 for that. Please check L<WWW::Mechanize::FAQ/"JavaScript"> for more.
105  
106 =head1 IMPORTANT LINKS
107  
108 =over 4
109  
110 =item * L<http://code.google.com/p/www-mechanize/issues/list>
111  
112 The queue for bugs & enhancements in WWW::Mechanize and
113 Test::WWW::Mechanize. Please note that the queue at L<http://rt.cpan.org>
114 is no longer maintained.
115  
116 =item * L<http://search.cpan.org/dist/WWW-Mechanize/>
117  
118 The CPAN documentation page for Mechanize.
119  
120 =item * L<http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize/FAQ.pod>
121  
122 Frequently asked questions. Make sure you read here FIRST.
123  
124 =back
125  
126 =cut
127  
128 47 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
129 47 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
130  
131 47 ▶use HTTP::Request 1.30;
Subroutine BEGIN: called CC=1 SCAR=0.0
132 47 ▶use LWP::UserAgent 5.827;
Subroutine BEGIN: called CC=1 SCAR=0.0
133 47 ▶use HTML::Form 1.00;
Subroutine BEGIN: called CC=1 SCAR=0.0
134 47 ▶use HTML::TokeParser;
Subroutine BEGIN: called CC=1 SCAR=0.0
135  
136 47 ▶use base 'LWP::UserAgent';
Subroutine BEGIN: called CC=1 SCAR=0.0
137  
138 47 our $HAS_ZLIB;
139 BEGIN {
140 47 ▶ $HAS_ZLIB = eval 'use Compress::Zlib (); 1;';
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
141 }
142  
143 =head1 CONSTRUCTOR AND STARTUP
144  
145 =head2 new()
146  
147 Creates and returns a new WWW::Mechanize object, hereafter referred to as
148 the "agent".
149  
150 my $mech = WWW::Mechanize->new()
151  
152 The constructor for WWW::Mechanize overrides two of the parms to the
153 LWP::UserAgent constructor:
154  
155 agent => 'WWW-Mechanize/#.##'
156 cookie_jar => {} # an empty, memory-only HTTP::Cookies object
157  
158 You can override these overrides by passing parms to the constructor,
159 as in:
160  
161 my $mech = WWW::Mechanize->new( agent => 'wonderbot 1.01' );
162  
163 If you want none of the overhead of a cookie jar, or don't want your
164 bot accepting cookies, you have to explicitly disallow it, like so:
165  
166 my $mech = WWW::Mechanize->new( cookie_jar => undef );
167  
168 Here are the parms that WWW::Mechanize recognizes. These do not include
169 parms that L<LWP::UserAgent> recognizes.
170  
171 =over 4
172  
173 =item * C<< autocheck => [0|1] >>
174  
175 Checks each request made to see if it was successful. This saves
176 you the trouble of manually checking yourself. Any errors found
177 are errors, not warnings.
178  
179 The default value is ON, unless it's being subclassed, in which
180 case it is OFF. This means that standalone L<WWW::Mechanize>instances
181 have autocheck turned on, which is protective for the vast majority
182 of Mech users who don't bother checking the return value of get()
183 and post() and can't figure why their code fails. However, if
184 L<WWW::Mechanize> is subclassed, such as for L<Test::WWW::Mechanize>
185 or L<Test::WWW::Mechanize::Catalyst>, this may not be an appropriate
186 default, so it's off.
187  
188 =item * C<< noproxy => [0|1] >>
189  
190 Turn off the automatic call to the L<LWP::UserAgent> C<env_proxy> function.
191  
192 This needs to be explicitly turned off if you're using L<Crypt::SSLeay> to
193 access a https site via a proxy server. Note: you still need to set your
194 HTTPS_PROXY environment variable as appropriate.
195  
196 =item * C<< onwarn => \&func >>
197  
198 Reference to a C<warn>-compatible function, such as C<< L<Carp>::carp >>,
199 that is called when a warning needs to be shown.
200  
201 If this is set to C<undef>, no warnings will ever be shown. However,
202 it's probably better to use the C<quiet> method to control that behavior.
203  
204 If this value is not passed, Mech uses C<Carp::carp> if L<Carp> is
205 installed, or C<CORE::warn> if not.
206  
207 =item * C<< onerror => \&func >>
208  
209 Reference to a C<die>-compatible function, such as C<< L<Carp>::croak >>,
210 that is called when there's a fatal error.
211  
212 If this is set to C<undef>, no errors will ever be shown.
213  
214 If this value is not passed, Mech uses C<Carp::croak> if L<Carp> is
215 installed, or C<CORE::die> if not.
216  
217 =item * C<< quiet => [0|1] >>
218  
219 Don't complain on warnings. Setting C<< quiet => 1 >> is the same as
220 calling C<< $mech->quiet(1) >>. Default is off.
221  
222 =item * C<< stack_depth => $value >>
223  
224 Sets the depth of the page stack that keeps track of all the
225 downloaded pages. Default is effectively infinite stack size. If
226 the stack is eating up your memory, then set this to a smaller
227 number, say 5 or 10. Setting this to zero means Mech will keep no
228 history.
229  
230 =back
231  
232 To support forms, WWW::Mechanize's constructor pushes POST
233 on to the agent's C<requests_redirectable> list (see also
234 L<LWP::UserAgent>.)
235  
236 =cut
237  
238 sub new {
239 45 ▶ my $class = shift;
Subroutine new: called CC=7 SCAR=19.5
Pod documented
240  
241 45 my %parent_parms = (
242 agent => "WWW-Mechanize/$VERSION",
243 cookie_jar => {},
244 );
245  
246 45 ▶ my %mech_parms = (
Branch: 1 branch
BranchTrueFalseTotal
$class eq 'WWW::Mechanize' ? : 45 0 45
247 autocheck => ($class eq 'WWW::Mechanize' ? 1 : 0),
248 onwarn => \&WWW::Mechanize::_warn,
249 onerror => \&WWW::Mechanize::_die,
250 quiet => 0,
251 stack_depth => 8675309, # Arbitrarily humongous stack
252 headers => {},
253 noproxy => 0,
254 );
255  
256 45 my %passed_parms = @_;
257  
258 # Keep the mech-specific parms before creating the object.
259 45 ▶ while ( my($key,$value) = each %passed_parms ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %passed_parms) 24 45 69
260 24 ▶ if ( exists $mech_parms{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $mech_parms{$key}) { } 5 19 24
261 5 $mech_parms{$key} = $value;
262 }
263 else {
264 19 $parent_parms{$key} = $value;
265 }
266 }
267  
268 45 my $self = $class->SUPER::new( %parent_parms );
269 45 bless $self, $class;
270  
271 # Use the mech parms now that we have a mech object.
272 45 for my $parm ( keys %mech_parms ) {
273 315 $self->{$parm} = $mech_parms{$parm};
274 }
275 45 $self->{page_stack} = [];
276 45 ▶ $self->env_proxy() unless $mech_parms{noproxy};
Branch: 1 branch
BranchTrueFalseTotal
unless $mech_parms{"noproxy"} 45 0 45
277  
278 # libwww-perl 5.800 (and before, I assume) has a problem where
279 # $ua->{proxy} can be undef and clone() doesn't handle it.
280 45 ▶ $self->{proxy} = {} unless defined $self->{proxy};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"proxy"} 0 45 45
281 45 push( @{$self->requests_redirectable}, 'POST' );
282  
283 45 $self->_reset_page();
284  
285 45 return $self;
286 }
287  
288 =head2 $mech->agent_alias( $alias )
289  
290 Sets the user agent string to the expanded version from a table of actual user strings.
291 I<$alias> can be one of the following:
292  
293 =over 4
294  
295 =item * Windows IE 6
296  
297 =item * Windows Mozilla
298  
299 =item * Mac Safari
300  
301 =item * Mac Mozilla
302  
303 =item * Linux Mozilla
304  
305 =item * Linux Konqueror
306  
307 =back
308  
309 then it will be replaced with a more interesting one. For instance,
310  
311 $mech->agent_alias( 'Windows IE 6' );
312  
313 sets your User-Agent to
314  
315 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
316  
317 The list of valid aliases can be returned from C<known_agent_aliases()>. The current list is:
318  
319 =over
320  
321 =item * Windows IE 6
322  
323 =item * Windows Mozilla
324  
325 =item * Mac Safari
326  
327 =item * Mac Mozilla
328  
329 =item * Linux Mozilla
330  
331 =item * Linux Konqueror
332  
333 =back
334  
335 =cut
336  
337 47 my %known_agents = (
338 'Windows IE 6' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
339 'Windows Mozilla' => 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6',
340 'Mac Safari' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/85 (KHTML, like Gecko) Safari/85',
341 'Mac Mozilla' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4a) Gecko/20030401',
342 'Linux Mozilla' => 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030624',
343 'Linux Konqueror' => 'Mozilla/5.0 (compatible; Konqueror/3; Linux)',
344 );
345  
346 sub agent_alias {
347 2 ▶ my $self = shift;
Subroutine agent_alias: called CC=2 SCAR=6.9
Pod documented
348 2 my $alias = shift;
349  
350 2 ▶ if ( defined $known_agents{$alias} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $known_agents{$alias}) { } 1 1 2
351 1 return $self->agent( $known_agents{$alias} );
352 }
353 else {
354 1 $self->warn( qq{Unknown agent alias "$alias"} );
355 1 return $self->agent();
356 }
357 }
358  
359 =head2 known_agent_aliases()
360  
361 Returns a list of all the agent aliases that Mech knows about.
362  
363 =cut
364  
365 sub known_agent_aliases {
366 1 ▶ return sort keys %known_agents;
Subroutine known_agent_aliases: called CC=1 SCAR=0.0
Pod documented
367 }
368  
369 =head1 PAGE-FETCHING METHODS
370  
371 =head2 $mech->get( $uri )
372  
373 Given a URL/URI, fetches it. Returns an L<HTTP::Response> object.
374 I<$uri> can be a well-formed URL string, a L<URI> object, or a
375 L<WWW::Mechanize::Link> object.
376  
377 The results are stored internally in the agent object, but you don't
378 know that. Just use the accessors listed below. Poking at the
379 internals is deprecated and subject to change in the future.
380  
381 C<get()> is a well-behaved overloaded version of the method in
382 L<LWP::UserAgent>. This lets you do things like
383  
384 $mech->get( $uri, ':content_file' => $tempfile );
385  
386 and you can rest assured that the parms will get filtered down
387 appropriately.
388  
389 B<NOTE:> Because C<:content_file> causes the page contents to be
390 stored in a file instead of the response object, some Mech functions
391 that expect it to be there won't work as expected. Use with caution.
392  
393 =cut
394  
395 sub get {
396 35 ▶ my $self = shift;
Subroutine get: called CC=3 SCAR=11.0
Pod documented
397 35 my $uri = shift;
398  
399 35 ▶ $uri = $uri->url if ref($uri) eq 'WWW::Mechanize::Link';
Branch: 1 branch
BranchTrueFalseTotal
if ref $uri eq "WWW::Mechanize::Link" 0 35 35
400  
401 35 ▶ $uri = $self->base
Branch: 1 branch
BranchTrueFalseTotal
$self->base ? : 12 23 35
402 ? URI->new_abs( $uri, $self->base )
403 : URI->new( $uri );
404  
405 # It appears we are returning a super-class method,
406 # but it in turn calls the request() method here in Mechanize
407 35 return $self->SUPER::get( $uri->as_string, @_ );
408 }
409  
410 =head2 $mech->put( $uri, content => $content )
411  
412 PUTs I<$content> to $uri. Returns an L<HTTP::Response> object.
413 I<$uri> can be a well-formed URI string, a L<URI> object, or a
414 L<WWW::Mechanize::Link> object.
415  
416 =cut
417  
418 sub put {
419 0 ▶ my $self = shift;
Subroutine put: not called CC=3 SCAR=24.8
Pod documented
420 0 my $uri = shift;
421  
422 0 ▶ $uri = $uri->url if ref($uri) eq 'WWW::Mechanize::Link';
Branch: 1 branch
BranchTrueFalseTotal
if ref $uri eq "WWW::Mechanize::Link" 0 0 0
423  
424 0 ▶ $uri = $self->base
Branch: 1 branch
BranchTrueFalseTotal
$self->base ? : 0 0 0
425 ? URI->new_abs( $uri, $self->base )
426 : URI->new( $uri );
427  
428 # It appears we are returning a super-class method,
429 # but it in turn calls the request() method here in Mechanize
430 0 return $self->_SUPER_put( $uri->as_string, @_ );
431 }
432  
433  
434 # Added until LWP::UserAgent has it.
435 sub _SUPER_put {
436 0 ▶ require HTTP::Request::Common;
Subroutine _SUPER_put: not called CC=1 SCAR=6.9
437 0 my($self, @parameters) = @_;
438 0 my @suff = $self->_process_colonic_headers(\@parameters,1);
439 0 return $self->request( HTTP::Request::Common::PUT( @parameters ), @suff );
440 }
441  
442 =head2 $mech->reload()
443  
444 Acts like the reload button in a browser: repeats the current
445 request. The history (as per the L</back> method) is not altered.
446  
447 Returns the L<HTTP::Response> object from the reload, or C<undef>
448 if there's no current request.
449  
450 =cut
451  
452 sub reload {
453 0 ▶ my $self = shift;
Subroutine reload: not called CC=2 SCAR=17.9
Pod documented
454  
455 0 ▶ return unless my $req = $self->{req};
Branch: 1 branch
BranchTrueFalseTotal
unless my $req = $self->{"req"} 0 0 0
456  
457 0 return $self->_update_page( $req, $self->_make_request( $req, @_ ) );
458 }
459  
460 =head2 $mech->back()
461  
462 The equivalent of hitting the "back" button in a browser. Returns to
463 the previous page. Won't go back past the first page. (Really, what
464 would it do if it could?)
465  
466 Returns true if it could go back, or false if not.
467  
468 =cut
469  
470 sub back {
471 1 ▶ my $self = shift;
Subroutine back: called CC=3 SCAR=11.2
Pod documented
472  
473 1 my $stack = $self->{page_stack};
474 1 ▶ return unless $stack && @{$stack};
Branch: 1 branch
BranchTrueFalseTotal
unless $stack and @{$stack;} 0 1 1
Condition33%1/3
$stack and @{$stack;}
!ll&&!rl&&r
001
MC/DC0%0/2
$stack and @{$stack;}
$stack @{$stack;}
Truth table33%1/3
A and B
A= $stackB= @{$stack;}
ABresult
0X0
100
111
475  
476 1 my $popped = pop @{$self->{page_stack}};
477 1 my $req = $popped->{req};
478 1 my $res = $popped->{res};
479  
480 1 $self->_update_page( $req, $res );
481  
482 1 return 1;
483 }
484  
485 =head1 STATUS METHODS
486  
487 =head2 $mech->success()
488  
489 Returns a boolean telling whether the last request was successful.
490 If there hasn't been an operation yet, returns false.
491  
492 This is a convenience function that wraps C<< $mech->res->is_success >>.
493  
494 =cut
495  
496 sub success {
497 21 ▶ my $self = shift;
Subroutine success: called CC=2 SCAR=6.9
Pod documented
498  
499 21 ▶ return $self->res && $self->res->is_success;
Condition100%3/3
$self->res && $self->res->is_success
!ll&&!rl&&r
1119
MC/DC100%2/2
$self->res && $self->res->is_success
$self->res $self->res->is_success
Truth table100%3/3
A && B
A= $self->resB= $self->res->is_success
ABresult
0X0
100
111
500 }
501  
502  
503 =head2 $mech->uri()
504  
505 Returns the current URI as a L<URI> object. This object stringifies
506 to the URI itself.
507  
508 =head2 $mech->response() / $mech->res()
509  
510 Return the current response as an L<HTTP::Response> object.
511  
512 Synonym for C<< $mech->response() >>
513  
514 =head2 $mech->status()
515  
516 Returns the HTTP status code of the response. This is a 3-digit
517 number like 200 for OK, 404 for not found, and so on.
518  
519 =head2 $mech->ct() / $mech->content_type()
520  
521 Returns the content type of the response.
522  
523 =head2 $mech->base()
524  
525 Returns the base URI for the current response
526  
527 =head2 $mech->forms()
528  
529 When called in a list context, returns a list of the forms found in
530 the last fetched page. In a scalar context, returns a reference to
531 an array with those forms. The forms returned are all L<HTML::Form>
532 objects.
533  
534 =head2 $mech->current_form()
535  
536 Returns the current form as an L<HTML::Form> object.
537  
538 =head2 $mech->links()
539  
540 When called in a list context, returns a list of the links found in the
541 last fetched page. In a scalar context it returns a reference to an array
542 with those links. Each link is a L<WWW::Mechanize::Link> object.
543  
544 =head2 $mech->is_html()
545  
546 Returns true/false on whether our content is HTML, according to the
547 HTTP headers.
548  
549 =cut
550  
551 sub uri {
552 0 ▶ my $self = shift;
Subroutine uri: not called CC=1 SCAR=6.9
Pod documented
553 0 return $self->response->request->uri;
554 }
555  
556 42 ▶sub res { my $self = shift; return $self->{res}; }
Subroutine res: called CC=1 SCAR=0.0
Pod documented
557 6 ▶sub response { my $self = shift; return $self->{res}; }
Subroutine response: called CC=1 SCAR=0.0
Pod documented
558 7 ▶sub status { my $self = shift; return $self->{status}; }
Subroutine status: called CC=1 SCAR=0.0
Pod documented
559 143 ▶sub ct { my $self = shift; return $self->{ct}; }
Subroutine ct: called CC=1 SCAR=0.0
Pod documented
560 1 ▶sub content_type { my $self = shift; return $self->{ct}; }
Subroutine content_type: called CC=1 SCAR=0.0
Pod documented
561 124 ▶sub base { my $self = shift; return $self->{base}; }
Subroutine base: called CC=1 SCAR=0.0
Pod documented
562 sub is_html {
563 65 ▶ my $self = shift;
Subroutine is_html: called CC=3 SCAR=11.4
Pod documented
564 65 ▶ return defined $self->ct &&
Condition66%4/6
defined $self->ct && ($self->ct eq 'text/html' || $self->ct eq 'application/xhtml+xml')
!ll&&!rl&&r
01352
$self->ct eq "text/html" or $self->ct eq "application/xhtml+xml"
l!l&&r!l&&!r
52013
MC/DC33%1/3
defined $self->ct && ($self->ct eq 'text/html' || $self->ct eq 'application/xhtml+xml')
defined $self->ct $self->ct eq "text/html" $self->ct eq "application/xhtml+xml"
Truth table50%2/4
A && B or C
A= defined $self->ctB= $self->ct eq "text/html"C= $self->ct eq "application/xhtml+xml"
ABCresult
0XX0
1000
11X1
1011
565 ($self->ct eq 'text/html' || $self->ct eq 'application/xhtml+xml');
566 }
567  
568 =head2 $mech->title()
569  
570 Returns the contents of the C<< <TITLE> >> tag, as parsed by
571 L<HTML::HeadParser>. Returns undef if the content is not HTML.
572  
573 =cut
574  
575 sub title {
576 5 ▶ my $self = shift;
Subroutine title: called CC=3 SCAR=11.1
Pod documented
577  
578 5 ▶ return unless $self->is_html;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_html 0 5 5
579  
580 5 ▶ if ( not defined $self->{title} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"title"}) 5 0 5
581 5 require HTML::HeadParser;
582 5 my $p = HTML::HeadParser->new;
583 5 $p->parse($self->content);
584 5 $self->{title} = $p->header('Title');
585 }
586 5 return $self->{title};
587 }
588  
589 =head1 CONTENT-HANDLING METHODS
590  
591 =head2 $mech->content(...)
592  
593 Returns the content that the mech uses internally for the last page
594 fetched. Ordinarily this is the same as
595 C<< $mech->response()->decoded_content() >>,
596 but this may differ for HTML documents if L</update_html> is
597 overloaded (in which case the value passed to the base-class
598 implementation of same will be returned), and/or extra named arguments
599 are passed to I<content()>:
600  
601 =over 2
602  
603 =item I<< $mech->content( format => 'text' ) >>
604  
605 Returns a text-only version of the page, with all HTML markup
606 stripped. This feature requires I<HTML::TreeBuilder> to be installed,
607 or a fatal error will be thrown. This works only if the contents are
608 HTML.
609  
610 =item I<< $mech->content( base_href => [$base_href|undef] ) >>
611  
612 Returns the HTML document, modified to contain a
613 C<< <base href="$base_href"> >> mark-up in the header.
614 I<$base_href> is C<< $mech->base() >> if not specified. This is
615 handy to pass the HTML to e.g. L<HTML::Display>. This works only if
616 the contents are HTML.
617  
618  
619 =item I<< $mech->content( raw => 1 ) >>
620  
621 Returns C<< $self->response()->content() >>, i.e. the raw contents from the
622 response.
623  
624 =item I<< $mech->content( decoded_by_headers => 1 ) >>
625  
626 Returns the content after applying all C<Content-Encoding> headers but
627 with not additional mangling.
628  
629 =item I<< $mech->content( charset => $charset ) >>
630  
631 Returns C<< $self->response()->decoded_content(charset => $charset) >>
632 (see L<HTTP::Response> for details).
633  
634 =back
635  
636 To preserve backwards compatibility, additional parameters will be
637 ignored unless none of C<< raw | decoded_by_headers | charset >> is
638 specified and the text is HTML, in which case an error will be triggered.
639  
640 =cut
641  
642 sub content {
643 27 ▶ my $self = shift;
Subroutine content: called CC=9 SCAR=22.0
Pod documented
644 27 my %parms = @_;
645  
646 27 my $content = $self->{content};
647 27 ▶ if (delete $parms{raw}) {
Branch: 4 branches
BranchTrueFalseTotal
if (delete $parms{'raw'}) { } 1 26 27
elsif (delete $parms{'decoded_by_headers'}) { } 2 24 26
elsif (my $charset = delete $parms{'charset'}) { } 1 23 24
elsif ($self->is_html) { } 18 5 23
648 1 $content = $self->response()->content();
649 }
650 elsif (delete $parms{decoded_by_headers}) {
651 2 $content = $self->response()->decoded_content(charset => 'none');
652 }
653 elsif (my $charset = delete $parms{charset}) {
654 1 $content = $self->response()->decoded_content(charset => $charset);
655 }
656 elsif ( $self->is_html ) {
657 18 ▶ if ( exists $parms{base_href} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $parms{"base_href"}) 2 16 18
658 2 ▶ my $base_href = (delete $parms{base_href}) || $self->base;
Condition66%2/3
delete $parms{'base_href'} || $self->base
l!l&&r!l&&!r
110
MC/DC0%0/2
delete $parms{'base_href'} || $self->base
delete $parms{'base_href'} $self->base
Truth table66%2/3
A || B
A= delete $parms{'base_href'}B= $self->base
ABresult
1X1
011
000
659 2 $content=~s/<head>/<head>\n<base href="$base_href">/i;
660 }
661  
662 18 ▶ if ( my $format = delete $parms{format} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $format = delete $parms{"format"}) 1 17 18
663 1 ▶ if ( $format eq 'text' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq 'text') { } 1 0 1
664 1 $content = $self->text;
665 }
666 else {
667 0 $self->die( qq{Unknown "format" parameter "$format"} );
668 }
669 }
670  
671 18 $self->_check_unhandled_parms( %parms );
672 }
673  
674 27 return $content;
675 }
676  
677 =head2 $mech->text()
678  
679 Returns the text of the current HTML content. If the content isn't
680 HTML, $mech will die.
681  
682 The text is extracted by parsing the content, and then the extracted
683 text is cached, so don't worry about performance of calling this
684 repeatedly.
685  
686 =cut
687  
688 sub text {
689 1 ▶ my $self = shift;
Subroutine text: called CC=2 SCAR=6.9
Pod documented
690  
691 1 ▶ if ( not defined $self->{text} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"text"}) 1 0 1
692 1 require HTML::TreeBuilder;
693 1 my $tree = HTML::TreeBuilder->new();
694 1 $tree->parse( $self->content );
695 1 $tree->eof();
696 1 $tree->elementify(); # just for safety
697 1 $self->{text} = $tree->as_text();
698 1 $tree->delete;
699 }
700  
701 1 return $self->{text};
702 }
703  
704 sub _check_unhandled_parms {
705 18 ▶ my $self = shift;
Subroutine _check_unhandled_parms: called CC=2 SCAR=7.2
706 18 my %parms = @_;
707  
708 18 for my $cmd ( sort keys %parms ) {
709 0 $self->die( qq{Unknown named argument "$cmd"} );
710 }
711 }
712  
713 =head1 LINK METHODS
714  
715 =head2 $mech->links()
716  
717 Lists all the links on the current page. Each link is a
718 WWW::Mechanize::Link object. In list context, returns a list of all
719 links. In scalar context, returns an array reference of all links.
720  
721 =cut
722  
723 sub links {
724 54 ▶ my $self = shift;
Subroutine links: called CC=3 SCAR=11.3
Pod documented
725  
726 54 ▶ $self->_extract_links() unless $self->{links};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"links"} 7 47 54
727  
728 54 ▶ return @{$self->{links}} if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 54 0 54
729 0 return $self->{links};
730 }
731  
732 =head2 $mech->follow_link(...)
733  
734 Follows a specified link on the page. You specify the match to be
735 found using the same parms that C<L<find_link()>> uses.
736  
737 Here some examples:
738  
739 =over 4
740  
741 =item * 3rd link called "download"
742  
743 $mech->follow_link( text => 'download', n => 3 );
744  
745 =item * first link where the URL has "download" in it, regardless of case:
746  
747 $mech->follow_link( url_regex => qr/download/i );
748  
749 or
750  
751 $mech->follow_link( url_regex => qr/(?i:download)/ );
752  
753 =item * 3rd link on the page
754  
755 $mech->follow_link( n => 3 );
756  
757 =back
758  
759 Returns the result of the GET method (an HTTP::Response object) if
760 a link was found. If the page has no links, or the specified link
761 couldn't be found, returns undef.
762  
763 =cut
764  
765 sub follow_link {
766 0 ▶ my $self = shift;
Subroutine follow_link: not called CC=4 SCAR=30.0
Pod documented
767 0 my %parms = ( n=>1, @_ );
768  
769 0 ▶ if ( $parms{n} eq 'all' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parms{"n"} eq "all") 0 0 0
770 0 delete $parms{n};
771 0 $self->warn( q{follow_link(n=>"all") is not valid} );
772 }
773  
774 0 my $link = $self->find_link(%parms);
775 0 ▶ if ( $link ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($link) 0 0 0
776 0 return $self->get( $link->url );
777 }
778  
779 0 ▶ if ( $self->{autocheck} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"autocheck"}) 0 0 0
780 0 $self->die( 'Link not found' );
781 }
782  
783 0 return;
784 }
785  
786 =head2 $mech->find_link( ... )
787  
788 Finds a link in the currently fetched page. It returns a
789 L<WWW::Mechanize::Link> object which describes the link. (You'll
790 probably be most interested in the C<url()> property.) If it fails
791 to find a link it returns undef.
792  
793 You can take the URL part and pass it to the C<get()> method. If
794 that's your plan, you might as well use the C<follow_link()> method
795 directly, since it does the C<get()> for you automatically.
796  
797 Note that C<< <FRAME SRC="..."> >> tags are parsed out of the the HTML
798 and treated as links so this method works with them.
799  
800 You can select which link to find by passing in one or more of these
801 key/value pairs:
802  
803 =over 4
804  
805 =item * C<< text => 'string', >> and C<< text_regex => qr/regex/, >>
806  
807 C<text> matches the text of the link against I<string>, which must be an
808 exact match. To select a link with text that is exactly "download", use
809  
810 $mech->find_link( text => 'download' );
811  
812 C<text_regex> matches the text of the link against I<regex>. To select a
813 link with text that has "download" anywhere in it, regardless of case, use
814  
815 $mech->find_link( text_regex => qr/download/i );
816  
817 Note that the text extracted from the page's links are trimmed. For
818 example, C<< <a> foo </a> >> is stored as 'foo', and searching for
819 leading or trailing spaces will fail.
820  
821 =item * C<< url => 'string', >> and C<< url_regex => qr/regex/, >>
822  
823 Matches the URL of the link against I<string> or I<regex>, as appropriate.
824 The URL may be a relative URL, like F<foo/bar.html>, depending on how
825 it's coded on the page.
826  
827 =item * C<< url_abs => string >> and C<< url_abs_regex => regex >>
828  
829 Matches the absolute URL of the link against I<string> or I<regex>,
830 as appropriate. The URL will be an absolute URL, even if it's relative
831 in the page.
832  
833 =item * C<< name => string >> and C<< name_regex => regex >>
834  
835 Matches the name of the link against I<string> or I<regex>, as appropriate.
836  
837 =item * C<< id => string >> and C<< id_regex => regex >>
838  
839 Matches the attribute 'id' of the link against I<string> or
840 I<regex>, as appropriate.
841  
842 =item * C<< class => string >> and C<< class_regex => regex >>
843  
844 Matches the attribute 'class' of the link against I<string> or
845 I<regex>, as appropriate.
846  
847 =item * C<< tag => string >> and C<< tag_regex => regex >>
848  
849 Matches the tag that the link came from against I<string> or I<regex>,
850 as appropriate. The C<tag_regex> is probably most useful to check for
851 more than one tag, as in:
852  
853 $mech->find_link( tag_regex => qr/^(a|frame)$/ );
854  
855 The tags and attributes looked at are defined below, at
856 L<< $mech->find_link() : link format >>.
857  
858 =back
859  
860 If C<n> is not specified, it defaults to 1. Therefore, if you don't
861 specify any parms, this method defaults to finding the first link on the
862 page.
863  
864 Note that you can specify multiple text or URL parameters, which
865 will be ANDed together. For example, to find the first link with
866 text of "News" and with "cnn.com" in the URL, use:
867  
868 $mech->find_link( text => 'News', url_regex => qr/cnn\.com/ );
869  
870 The return value is a reference to an array containing a
871 L<WWW::Mechanize::Link> object for every link in C<< $self->content >>.
872  
873 The links come from the following:
874  
875 =over 4
876  
877 =item C<< <a href=...> >>
878  
879 =item C<< <area href=...> >>
880  
881 =item C<< <frame src=...> >>
882  
883 =item C<< <iframe src=...> >>
884  
885 =item C<< <link href=...> >>
886  
887 =item C<< <meta content=...> >>
888  
889 =back
890  
891 =cut
892  
893 sub find_link {
894 54 ▶ my $self = shift;
Subroutine find_link: called CC=8 SCAR=20.8
Pod documented
895 54 my %parms = ( n=>1, @_ );
896  
897 54 my $wantall = ( $parms{n} eq 'all' );
898  
899 54 $self->_clean_keys( \%parms, qr/^(n|(text|url|url_abs|name|tag|id|class)(_regex)?)$/ );
900  
901 54 ▶ my @links = $self->links or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@links) = $self->links or return 2 52 54
902  
903 52 my $nmatches = 0;
904 52 my @matches;
905 52 for my $link ( @links ) {
906 434 ▶ if ( _match_any_link_parms($link,\%parms) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_match_any_link_parms($link, \%parms)) 82 352 434
907 82 ▶ if ( $wantall ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wantall) { } 23 59 82
908 23 push( @matches, $link );
909 }
910 else {
911 59 ++$nmatches;
912 59 ▶ return $link if $nmatches >= $parms{n};
Branch: 1 branch
BranchTrueFalseTotal
if $nmatches >= $parms{"n"} 41 18 59
913 }
914 }
915 } # for @links
916  
917 11 ▶ if ( $wantall ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wantall) 6 5 11
918 6 ▶ return @matches if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 4 2 6
919 2 return \@matches;
920 }
921  
922 5 return;
923 } # find_link
924  
925 # Used by find_links to check for matches
926 # The logic is such that ALL parm criteria that are given must match
927 sub _match_any_link_parms {
928 434 ▶ my $link = shift;
Subroutine _match_any_link_parms: called CC=40 SCAR=37.1
929 434 my $p = shift;
930  
931 # No conditions, anything matches
932 434 ▶ return 1 unless keys %$p;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$p 0 434 434
933  
934 434 ▶ return if defined $p->{url} && !($link->url eq $p->{url} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url"} and not $link->url eq $p->{"url"} 76 358 434
Condition100%3/3
defined $p->{"url"} and not $link->url eq $p->{"url"}
!ll&&!rl&&r
356276
MC/DC100%2/2
defined $p->{"url"} and not $link->url eq $p->{"url"}
defined $p->{"url"} not $link->url eq $p->{"url"}
Truth table100%3/3
A and not(B)
A= defined $p->{"url"}B= not $link->url eq $p->{"url"}
ABresult
0X0
100
111
935 358 ▶ return if defined $p->{url_regex} && !($link->url =~ $p->{url_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_regex"} and not $link->url =~ /$p->{"url_regex"}/ 58 300 358
Condition100%3/3
defined $p->{"url_regex"} and not $link->url =~ /$p->{"url_regex"}/
!ll&&!rl&&r
2901058
MC/DC100%2/2
defined $p->{"url_regex"} and not $link->url =~ /$p->{"url_regex"}/
defined $p->{"url_regex"} not $link->url =~ /$p->{"url_regex"}/
Truth table100%3/3
A and not(B)
A= defined $p->{"url_regex"}B= not $link->url =~ /$p->{"url_regex"}/
ABresult
0X0
100
111
936 300 ▶ return if defined $p->{url_abs} && !($link->url_abs eq $p->{url_abs} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_abs"} and not $link->url_abs eq $p->{"url_abs"} 24 276 300
Condition66%2/3
defined $p->{"url_abs"} and not $link->url_abs eq $p->{"url_abs"}
!ll&&!rl&&r
276024
MC/DC50%1/2
defined $p->{"url_abs"} and not $link->url_abs eq $p->{"url_abs"}
defined $p->{"url_abs"} not $link->url_abs eq $p->{"url_abs"}
Truth table66%2/3
A and not(B)
A= defined $p->{"url_abs"}B= not $link->url_abs eq $p->{"url_abs"}
ABresult
0X0
100
111
937 276 ▶ return if defined $p->{url_abs_regex} && !($link->url_abs =~ $p->{url_abs_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_abs_regex"} and not $link->url_abs =~ /$p->{"url_abs_regex"}/ 23 253 276
Condition100%3/3
defined $p->{"url_abs_regex"} and not $link->url_abs =~ /$p->{"url_abs_regex"}/
!ll&&!rl&&r
252123
MC/DC100%2/2
defined $p->{"url_abs_regex"} and not $link->url_abs =~ /$p->{"url_abs_regex"}/
defined $p->{"url_abs_regex"} not $link->url_abs =~ /$p->{"url_abs_regex"}/
Truth table100%3/3
A and not(B)
A= defined $p->{"url_abs_regex"}B= not $link->url_abs =~ /$p->{"url_abs_regex"}/
ABresult
0X0
100
111
938 253 ▶ return if defined $p->{text} && !(defined($link->text) && $link->text eq $p->{text} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"text"} and not defined $link->text && $link->text eq $p->{"text"} 61 192 253
Condition100%6/6
defined $p->{"text"} and not defined $link->text && $link->text eq $p->{"text"}
!ll&&!rl&&r
187561
defined $link->text && $link->text eq $p->{'text'}
!ll&&!rl&&r
24375
MC/DC100%3/3
defined $p->{"text"} and not defined $link->text && $link->text eq $p->{"text"}
defined $p->{"text"} defined $link->text $link->text eq $p->{'text'}
Truth table100%4/4
A and not(B && C)
A= defined $p->{"text"}B= defined $link->textC= $link->text eq $p->{'text'}
ABCresult
0XX0
1110
10X1
1101
939 192 ▶ return if defined $p->{text_regex} && !(defined($link->text) && $link->text =~ $p->{text_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"text_regex"} and not defined $link->text && $link->text =~ /$p->{"text_regex"}/ 74 118 192
Condition100%6/6
defined $p->{"text_regex"} and not defined $link->text && $link->text =~ /$p->{"text_regex"}/
!ll&&!rl&&r
1011774
defined $link->text && $link->text =~ /$p->{'text_regex'}/
!ll&&!rl&&r
383617
MC/DC100%3/3
defined $p->{"text_regex"} and not defined $link->text && $link->text =~ /$p->{"text_regex"}/
defined $p->{"text_regex"} defined $link->text $link->text =~ /$p->{'text_regex'}/
Truth table100%4/4
A and not(B && C)
A= defined $p->{"text_regex"}B= defined $link->textC= $link->text =~ /$p->{'text_regex'}/
ABCresult
0XX0
1110
10X1
1101
940 118 ▶ return if defined $p->{name} && !(defined($link->name) && $link->name eq $p->{name} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"name"} and not defined $link->name && $link->name eq $p->{"name"} 8 110 118
Condition83%5/6
defined $p->{"name"} and not defined $link->name && $link->name eq $p->{"name"}
!ll&&!rl&&r
10918
defined $link->name && $link->name eq $p->{'name'}
!ll&&!rl&&r
801
MC/DC66%2/3
defined $p->{"name"} and not defined $link->name && $link->name eq $p->{"name"}
defined $p->{"name"} defined $link->name $link->name eq $p->{'name'}
Truth table75%3/4
A and not(B && C)
A= defined $p->{"name"}B= defined $link->nameC= $link->name eq $p->{'name'}
ABCresult
0XX0
1110
10X1
1101
941 110 ▶ return if defined $p->{name_regex} && !(defined($link->name) && $link->name =~ $p->{name_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"name_regex"} and not defined $link->name && $link->name =~ /$p->{"name_regex"}/ 14 96 110
Condition100%6/6
defined $p->{"name_regex"} and not defined $link->name && $link->name =~ /$p->{"name_regex"}/
!ll&&!rl&&r
94214
defined $link->name && $link->name =~ /$p->{'name_regex'}/
!ll&&!rl&&r
1222
MC/DC100%3/3
defined $p->{"name_regex"} and not defined $link->name && $link->name =~ /$p->{"name_regex"}/
defined $p->{"name_regex"} defined $link->name $link->name =~ /$p->{'name_regex'}/
Truth table100%4/4
A and not(B && C)
A= defined $p->{"name_regex"}B= defined $link->nameC= $link->name =~ /$p->{'name_regex'}/
ABCresult
0XX0
1110
10X1
1101
942 96 ▶ return if defined $p->{tag} && !($link->tag && $link->tag eq $p->{tag} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"tag"} and not $link->tag && $link->tag eq $p->{"tag"} 3 93 96
Condition83%5/6
defined $p->{"tag"} and not $link->tag && $link->tag eq $p->{"tag"}
!ll&&!rl&&r
8673
$link->tag && $link->tag eq $p->{'tag'}
!ll&&!rl&&r
037
MC/DC66%2/3
defined $p->{"tag"} and not $link->tag && $link->tag eq $p->{"tag"}
defined $p->{"tag"} $link->tag $link->tag eq $p->{'tag'}
Truth table75%3/4
A and not(B && C)
A= defined $p->{"tag"}B= $link->tagC= $link->tag eq $p->{'tag'}
ABCresult
0XX0
1110
10X1
1101
943 93 ▶ return if defined $p->{tag_regex} && !($link->tag && $link->tag =~ $p->{tag_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"tag_regex"} and not $link->tag && $link->tag =~ /$p->{"tag_regex"}/ 3 90 93
Condition83%5/6
defined $p->{"tag_regex"} and not $link->tag && $link->tag =~ /$p->{"tag_regex"}/
!ll&&!rl&&r
8373
$link->tag && $link->tag =~ /$p->{'tag_regex'}/
!ll&&!rl&&r
037
MC/DC66%2/3
defined $p->{"tag_regex"} and not $link->tag && $link->tag =~ /$p->{"tag_regex"}/
defined $p->{"tag_regex"} $link->tag $link->tag =~ /$p->{'tag_regex'}/
Truth table75%3/4
A and not(B && C)
A= defined $p->{"tag_regex"}B= $link->tagC= $link->tag =~ /$p->{'tag_regex'}/
ABCresult
0XX0
1110
10X1
1101
944  
945 90 ▶ return if defined $p->{id} && !($link->attrs->{id} && $link->attrs->{id} eq $p->{id} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"id"} and not $link->attrs->{"id"} && $link->attrs->{"id"} eq $p->{"id"} 3 87 90
Condition83%5/6
defined $p->{"id"} and not $link->attrs->{"id"} && $link->attrs->{"id"} eq $p->{"id"}
!ll&&!rl&&r
8613
$link->attrs->{'id'} && $link->attrs->{'id'} eq $p->{'id'}
!ll&&!rl&&r
301
MC/DC66%2/3
defined $p->{"id"} and not $link->attrs->{"id"} && $link->attrs->{"id"} eq $p->{"id"}
defined $p->{"id"} $link->attrs->{'id'} $link->attrs->{'id'} eq $p->{'id'}
Truth table75%3/4
A and not(B && C)
A= defined $p->{"id"}B= $link->attrs->{'id'}C= $link->attrs->{'id'} eq $p->{'id'}
ABCresult
0XX0
1110
10X1
1101
946 87 ▶ return if defined $p->{id_regex} && !($link->attrs->{id} && $link->attrs->{id} =~ $p->{id_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"id_regex"} and not $link->attrs->{"id"} && $link->attrs->{"id"} =~ /$p->{"id_regex"}/ 3 84 87
Condition83%5/6
defined $p->{"id_regex"} and not $link->attrs->{"id"} && $link->attrs->{"id"} =~ /$p->{"id_regex"}/
!ll&&!rl&&r
8313
$link->attrs->{'id'} && $link->attrs->{'id'} =~ /$p->{'id_regex'}/
!ll&&!rl&&r
301
MC/DC66%2/3
defined $p->{"id_regex"} and not $link->attrs->{"id"} && $link->attrs->{"id"} =~ /$p->{"id_regex"}/
defined $p->{"id_regex"} $link->attrs->{'id'} $link->attrs->{'id'} =~ /$p->{'id_regex'}/
Truth table75%3/4
A and not(B && C)
A= defined $p->{"id_regex"}B= $link->attrs->{'id'}C= $link->attrs->{'id'} =~ /$p->{'id_regex'}/
ABCresult
0XX0
1110
10X1
1101
947 84 ▶ return if defined $p->{class} && !($link->attrs->{class} && $link->attrs->{class} eq $p->{class} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"class"} and not $link->attrs->{"class"} && $link->attrs->{"class"} eq $p->{"class"} 1 83 84
Condition83%5/6
defined $p->{"class"} and not $link->attrs->{"class"} && $link->attrs->{"class"} eq $p->{"class"}
!ll&&!rl&&r
8211
$link->attrs->{'class'} && $link->attrs->{'class'} eq $p->{'class'}
!ll&&!rl&&r
101
MC/DC66%2/3
defined $p->{"class"} and not $link->attrs->{"class"} && $link->attrs->{"class"} eq $p->{"class"}
defined $p->{"class"} $link->attrs->{'class'} $link->attrs->{'class'} eq $p->{'class'}
Truth table75%3/4
A and not(B && C)
A= defined $p->{"class"}B= $link->attrs->{'class'}C= $link->attrs->{'class'} eq $p->{'class'}
ABCresult
0XX0
1110
10X1
1101
948 83 ▶ return if defined $p->{class_regex} && !($link->attrs->{class} && $link->attrs->{class} =~ $p->{class_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"class_regex"} and not $link->attrs->{"class"} && $link->attrs->{"class"} =~ /$p->{"class_regex"}/ 1 82 83
Condition83%5/6
defined $p->{"class_regex"} and not $link->attrs->{"class"} && $link->attrs->{"class"} =~ /$p->{"class_regex"}/
!ll&&!rl&&r
8111
$link->attrs->{'class'} && $link->attrs->{'class'} =~ /$p->{'class_regex'}/
!ll&&!rl&&r
101
MC/DC66%2/3
defined $p->{"class_regex"} and not $link->attrs->{"class"} && $link->attrs->{"class"} =~ /$p->{"class_regex"}/
defined $p->{"class_regex"} $link->attrs->{'class'} $link->attrs->{'class'} =~ /$p->{'class_regex'}/
Truth table75%3/4
A and not(B && C)
A= defined $p->{"class_regex"}B= $link->attrs->{'class'}C= $link->attrs->{'class'} =~ /$p->{'class_regex'}/
ABCresult
0XX0
1110
10X1
1101
949  
950 # Success: everything that was defined passed.
951 82 return 1;
952  
953 }
954  
955 # Cleans the %parms parameter for the find_link and find_image methods.
956 sub _clean_keys {
957 55 ▶ my $self = shift;
Subroutine _clean_keys: called CC=7 SCAR=19.5
958 55 my $parms = shift;
959 55 my $rx_keyname = shift;
960  
961 55 for my $key ( keys %$parms ) {
962 106 my $val = $parms->{$key};
963 106 ▶ if ( $key !~ qr/$rx_keyname/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($key =~ qr/$rx_keyname/) 5 101 106
964 5 $self->warn( qq{Unknown link-finding parameter "$key"} );
965 5 delete $parms->{$key};
966 5 next;
967 }
968  
969 101 my $key_regex = ( $key =~ /_regex$/ );
970 101 my $val_regex = ( ref($val) eq 'Regexp' );
971  
972 101 ▶ if ( $key_regex ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_regex) { } 21 80 101
973 21 ▶ if ( !$val_regex ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($val_regex) 5 16 21
974 5 $self->warn( qq{$val passed as $key is not a regex} );
975 5 delete $parms->{$key};
976 5 next;
977 }
978 }
979 else {
980 80 ▶ if ( $val_regex ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val_regex) 4 76 80
981 4 $self->warn( qq{$val passed as '$key' is a regex} );
982 4 delete $parms->{$key};
983 4 next;
984 }
985 76 ▶ if ( $val =~ /^\s|\s$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /^\s|\s$/) 4 72 76
986 4 $self->warn( qq{'$val' is space-padded and cannot succeed} );
987 4 delete $parms->{$key};
988 4 next;
989 }
990 }
991 } # for keys %parms
992  
993 55 return;
994 } # _clean_keys()
995  
996  
997 =head2 $mech->find_all_links( ... )
998  
999 Returns all the links on the current page that match the criteria. The
1000 method for specifying link criteria is the same as in C<L</find_link()>>.
1001 Each of the links returned is a L<WWW::Mechanize::Link> object.
1002  
1003 In list context, C<find_all_links()> returns a list of the links.
1004 Otherwise, it returns a reference to the list of links.
1005  
1006 C<find_all_links()> with no parameters returns all links in the
1007 page.
1008  
1009 =cut
1010  
1011 sub find_all_links {
1012 6 ▶ my $self = shift;
Subroutine find_all_links: called CC=1 SCAR=0.0
Pod documented
1013 6 return $self->find_link( @_, n=>'all' );
1014 }
1015  
1016 =head2 $mech->find_all_inputs( ... criteria ... )
1017  
1018 find_all_inputs() returns an array of all the input controls in the
1019 current form whose properties match all of the regexes passed in.
1020 The controls returned are all descended from HTML::Form::Input.
1021  
1022 If no criteria are passed, all inputs will be returned.
1023  
1024 If there is no current page, there is no form on the current
1025 page, or there are no submit controls in the current form
1026 then the return will be an empty array.
1027  
1028 You may use a regex or a literal string:
1029  
1030 # get all textarea controls whose names begin with "customer"
1031 my @customer_text_inputs = $mech->find_all_inputs(
1032 type => 'textarea',
1033 name_regex => qr/^customer/,
1034 );
1035  
1036 # get all text or textarea controls called "customer"
1037 my @customer_text_inputs = $mech->find_all_inputs(
1038 type_regex => qr/^(text|textarea)$/,
1039 name => 'customer',
1040 );
1041  
1042 =cut
1043  
1044 sub find_all_inputs {
1045 8 ▶ my $self = shift;
Subroutine find_all_inputs: called CC=8 SCAR=20.8
Pod documented
1046 8 my %criteria = @_;
1047  
1048 8 ▶ my $form = $self->current_form() or return;
Branch: 1 branch
BranchTrueFalseTotal
my $form = $self->current_form or return 0 8 8
1049  
1050 8 my @found;
1051 8 foreach my $input ( $form->inputs ) { # check every pattern for a match on the current hash
1052 34 my $matched = 1;
1053 34 foreach my $criterion ( sort keys %criteria ) { # Sort so we're deterministic
1054 22 my $field = $criterion;
1055 22 my $is_regex = ( $field =~ s/(?:_regex)$// );
1056 22 my $what = $input->{$field};
1057 $matched = defined($what) && (
1058 $is_regex
1059 ? ( $what =~ $criteria{$criterion} )
1060 22 ▶ : ( $what eq $criteria{$criterion} )
Branch: 1 branch
BranchTrueFalseTotal
$is_regex ? : 12 10 22
Condition66%2/3
defined $what && ($is_regex ? $what =~ /$criteria{$criterion}/ : $what eq $criteria{$criterion})
!ll&&!rl&&r
01111
MC/DC50%1/2
defined $what && ($is_regex ? $what =~ /$criteria{$criterion}/ : $what eq $criteria{$criterion})
defined $what ($is_regex ? $what =~ /$criteria{$criterion}/ : $what eq $criteria{$criterion})
Truth table66%2/3
A && B
A= defined $whatB= ($is_regex ? $what =~ /$criteria{$criterion}/ : $what eq $criteria{$criterion})
ABresult
0X0
100
111
1061 );
1062 22 ▶ last if !$matched;
Branch: 1 branch
BranchTrueFalseTotal
unless $matched 11 11 22
1063 }
1064 34 ▶ push @found, $input if $matched;
Branch: 1 branch
BranchTrueFalseTotal
if $matched 23 11 34
1065 }
1066 8 return @found;
1067 }
1068  
1069 =head2 $mech->find_all_submits( ... criteria ... )
1070  
1071 C<find_all_submits()> does the same thing as C<find_all_inputs()>
1072 except that it only returns controls that are submit controls,
1073 ignoring other types of input controls like text and checkboxes.
1074  
1075 =cut
1076  
1077 sub find_all_submits {
1078 2 ▶ my $self = shift;
Subroutine find_all_submits: called CC=1 SCAR=0.0
Pod documented
1079  
1080 2 return $self->find_all_inputs( @_, type_regex => qr/^(submit|image)$/ );
1081 }
1082  
1083  
1084 =head1 IMAGE METHODS
1085  
1086 =head2 $mech->images
1087  
1088 Lists all the images on the current page. Each image is a
1089 WWW::Mechanize::Image object. In list context, returns a list of all
1090 images. In scalar context, returns an array reference of all images.
1091  
1092 =cut
1093  
1094 sub images {
1095 3 ▶ my $self = shift;
Subroutine images: called CC=3 SCAR=11.3
Pod documented
1096  
1097 3 ▶ $self->_extract_images() unless $self->{images};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"images"} 2 1 3
1098  
1099 3 ▶ return @{$self->{images}} if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 3 0 3
1100 0 return $self->{images};
1101 }
1102  
1103 =head2 $mech->find_image()
1104  
1105 Finds an image in the current page. It returns a
1106 L<WWW::Mechanize::Image> object which describes the image. If it fails
1107 to find an image it returns undef.
1108  
1109 You can select which image to find by passing in one or more of these
1110 key/value pairs:
1111  
1112 =over 4
1113  
1114 =item * C<< alt => 'string' >> and C<< alt_regex => qr/regex/, >>
1115  
1116 C<alt> matches the ALT attribute of the image against I<string>, which must be an
1117 exact match. To select a image with an ALT tag that is exactly "download", use
1118  
1119 $mech->find_image( alt => 'download' );
1120  
1121 C<alt_regex> matches the ALT attribute of the image against a regular
1122 expression. To select an image with an ALT attribute that has "download"
1123 anywhere in it, regardless of case, use
1124  
1125 $mech->find_image( alt_regex => qr/download/i );
1126  
1127 =item * C<< url => 'string', >> and C<< url_regex => qr/regex/, >>
1128  
1129 Matches the URL of the image against I<string> or I<regex>, as appropriate.
1130 The URL may be a relative URL, like F<foo/bar.html>, depending on how
1131 it's coded on the page.
1132  
1133 =item * C<< url_abs => string >> and C<< url_abs_regex => regex >>
1134  
1135 Matches the absolute URL of the image against I<string> or I<regex>,
1136 as appropriate. The URL will be an absolute URL, even if it's relative
1137 in the page.
1138  
1139 =item * C<< tag => string >> and C<< tag_regex => regex >>
1140  
1141 Matches the tag that the image came from against I<string> or I<regex>,
1142 as appropriate. The C<tag_regex> is probably most useful to check for
1143 more than one tag, as in:
1144  
1145 $mech->find_image( tag_regex => qr/^(img|input)$/ );
1146  
1147 The tags supported are C<< <img> >> and C<< <input> >>.
1148  
1149 =back
1150  
1151 If C<n> is not specified, it defaults to 1. Therefore, if you don't
1152 specify any parms, this method defaults to finding the first image on the
1153 page.
1154  
1155 Note that you can specify multiple ALT or URL parameters, which
1156 will be ANDed together. For example, to find the first image with
1157 ALT text of "News" and with "cnn.com" in the URL, use:
1158  
1159 $mech->find_image( image => 'News', url_regex => qr/cnn\.com/ );
1160  
1161 The return value is a reference to an array containing a
1162 L<WWW::Mechanize::Image> object for every image in C<< $self->content >>.
1163  
1164 =cut
1165  
1166 sub find_image {
1167 1 ▶ my $self = shift;
Subroutine find_image: called CC=8 SCAR=24.4
Pod documented
1168 1 my %parms = ( n=>1, @_ );
1169  
1170 1 my $wantall = ( $parms{n} eq 'all' );
1171  
1172 1 $self->_clean_keys( \%parms, qr/^(n|(alt|url|url_abs|tag)(_regex)?)$/ );
1173  
1174 1 ▶ my @images = $self->images or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@images) = $self->images or return 0 1 1
1175  
1176 1 my $nmatches = 0;
1177 1 my @matches;
1178 1 for my $image ( @images ) {
1179 3 ▶ if ( _match_any_image_parms($image,\%parms) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_match_any_image_parms($image, \%parms)) 3 0 3
1180 3 ▶ if ( $wantall ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wantall) { } 3 0 3
1181 3 push( @matches, $image );
1182 }
1183 else {
1184 0 ++$nmatches;
1185 0 ▶ return $image if $nmatches >= $parms{n};
Branch: 1 branch
BranchTrueFalseTotal
if $nmatches >= $parms{"n"} 0 0 0
1186 }
1187 }
1188 } # for @images
1189  
1190 1 ▶ if ( $wantall ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wantall) 1 0 1
1191 1 ▶ return @matches if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 0 1
1192 0 return \@matches;
1193 }
1194  
1195 0 return;
1196 }
1197  
1198 # Used by find_images to check for matches
1199 # The logic is such that ALL parm criteria that are given must match
1200 sub _match_any_image_parms {
1201 3 ▶ my $image = shift;
Subroutine _match_any_image_parms: called CC=22 SCAR=46.8
1202 3 my $p = shift;
1203  
1204 # No conditions, anything matches
1205 3 ▶ return 1 unless keys %$p;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$p 0 3 3
1206  
1207 3 ▶ return if defined $p->{url} && !($image->url eq $p->{url} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url"} and not $image->url eq $p->{"url"} 0 3 3
Condition33%1/3
defined $p->{"url"} and not $image->url eq $p->{"url"}
!ll&&!rl&&r
300
MC/DC0%0/2
defined $p->{"url"} and not $image->url eq $p->{"url"}
defined $p->{"url"} not $image->url eq $p->{"url"}
Truth table33%1/3
A and not(B)
A= defined $p->{"url"}B= not $image->url eq $p->{"url"}
ABresult
0X0
100
111
1208 3 ▶ return if defined $p->{url_regex} && !($image->url =~ $p->{url_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_regex"} and not $image->url =~ /$p->{"url_regex"}/ 0 3 3
Condition33%1/3
defined $p->{"url_regex"} and not $image->url =~ /$p->{"url_regex"}/
!ll&&!rl&&r
300
MC/DC0%0/2
defined $p->{"url_regex"} and not $image->url =~ /$p->{"url_regex"}/
defined $p->{"url_regex"} not $image->url =~ /$p->{"url_regex"}/
Truth table33%1/3
A and not(B)
A= defined $p->{"url_regex"}B= not $image->url =~ /$p->{"url_regex"}/
ABresult
0X0
100
111
1209 3 ▶ return if defined $p->{url_abs} && !($image->url_abs eq $p->{url_abs} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_abs"} and not $image->url_abs eq $p->{"url_abs"} 0 3 3
Condition33%1/3
defined $p->{"url_abs"} and not $image->url_abs eq $p->{"url_abs"}
!ll&&!rl&&r
300
MC/DC0%0/2
defined $p->{"url_abs"} and not $image->url_abs eq $p->{"url_abs"}
defined $p->{"url_abs"} not $image->url_abs eq $p->{"url_abs"}
Truth table33%1/3
A and not(B)
A= defined $p->{"url_abs"}B= not $image->url_abs eq $p->{"url_abs"}
ABresult
0X0
100
111
1210 3 ▶ return if defined $p->{url_abs_regex} && !($image->url_abs =~ $p->{url_abs_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_abs_regex"} and not $image->url_abs =~ /$p->{"url_abs_regex"}/ 0 3 3
Condition33%1/3
defined $p->{"url_abs_regex"} and not $image->url_abs =~ /$p->{"url_abs_regex"}/
!ll&&!rl&&r
300
MC/DC0%0/2
defined $p->{"url_abs_regex"} and not $image->url_abs =~ /$p->{"url_abs_regex"}/
defined $p->{"url_abs_regex"} not $image->url_abs =~ /$p->{"url_abs_regex"}/
Truth table33%1/3
A and not(B)
A= defined $p->{"url_abs_regex"}B= not $image->url_abs =~ /$p->{"url_abs_regex"}/
ABresult
0X0
100
111
1211 3 ▶ return if defined $p->{alt} && !(defined($image->alt) && $image->alt eq $p->{alt} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"alt"} and not defined $image->alt && $image->alt eq $p->{"alt"} 0 3 3
Condition16%1/6
defined $p->{"alt"} and not defined $image->alt && $image->alt eq $p->{"alt"}
!ll&&!rl&&r
300
defined $image->alt && $image->alt eq $p->{'alt'}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"alt"} and not defined $image->alt && $image->alt eq $p->{"alt"}
defined $p->{"alt"} defined $image->alt $image->alt eq $p->{'alt'}
Truth table25%1/4
A and not(B && C)
A= defined $p->{"alt"}B= defined $image->altC= $image->alt eq $p->{'alt'}
ABCresult
0XX0
1110
10X1
1101
1212 3 ▶ return if defined $p->{alt_regex} && !(defined($image->alt) && $image->alt =~ $p->{alt_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"alt_regex"} and not defined $image->alt && $image->alt =~ /$p->{"alt_regex"}/ 0 3 3
Condition16%1/6
defined $p->{"alt_regex"} and not defined $image->alt && $image->alt =~ /$p->{"alt_regex"}/
!ll&&!rl&&r
300
defined $image->alt && $image->alt =~ /$p->{'alt_regex'}/
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"alt_regex"} and not defined $image->alt && $image->alt =~ /$p->{"alt_regex"}/
defined $p->{"alt_regex"} defined $image->alt $image->alt =~ /$p->{'alt_regex'}/
Truth table25%1/4
A and not(B && C)
A= defined $p->{"alt_regex"}B= defined $image->altC= $image->alt =~ /$p->{'alt_regex'}/
ABCresult
0XX0
1110
10X1
1101
1213 3 ▶ return if defined $p->{tag} && !($image->tag && $image->tag eq $p->{tag} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"tag"} and not $image->tag && $image->tag eq $p->{"tag"} 0 3 3
Condition16%1/6
defined $p->{"tag"} and not $image->tag && $image->tag eq $p->{"tag"}
!ll&&!rl&&r
300
$image->tag && $image->tag eq $p->{'tag'}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"tag"} and not $image->tag && $image->tag eq $p->{"tag"}
defined $p->{"tag"} $image->tag $image->tag eq $p->{'tag'}
Truth table25%1/4
A and not(B && C)
A= defined $p->{"tag"}B= $image->tagC= $image->tag eq $p->{'tag'}
ABCresult
0XX0
1110
10X1
1101
1214 3 ▶ return if defined $p->{tag_regex} && !($image->tag && $image->tag =~ $p->{tag_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"tag_regex"} and not $image->tag && $image->tag =~ /$p->{"tag_regex"}/ 0 3 3
Condition16%1/6
defined $p->{"tag_regex"} and not $image->tag && $image->tag =~ /$p->{"tag_regex"}/
!ll&&!rl&&r
300
$image->tag && $image->tag =~ /$p->{'tag_regex'}/
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"tag_regex"} and not $image->tag && $image->tag =~ /$p->{"tag_regex"}/
defined $p->{"tag_regex"} $image->tag $image->tag =~ /$p->{'tag_regex'}/
Truth table25%1/4
A and not(B && C)
A= defined $p->{"tag_regex"}B= $image->tagC= $image->tag =~ /$p->{'tag_regex'}/
ABCresult
0XX0
1110
10X1
1101
1215  
1216 # Success: everything that was defined passed.
1217 3 return 1;
1218 }
1219  
1220  
1221 =head2 $mech->find_all_images( ... )
1222  
1223 Returns all the images on the current page that match the criteria. The
1224 method for specifying image criteria is the same as in C<L</find_image()>>.
1225 Each of the images returned is a L<WWW::Mechanize::Image> object.
1226  
1227 In list context, C<find_all_images()> returns a list of the images.
1228 Otherwise, it returns a reference to the list of images.
1229  
1230 C<find_all_images()> with no parameters returns all images in the page.
1231  
1232 =cut
1233  
1234 sub find_all_images {
1235 1 ▶ my $self = shift;
Subroutine find_all_images: called CC=1 SCAR=0.0
Pod documented
1236 1 return $self->find_image( @_, n=>'all' );
1237 }
1238  
1239 =head1 FORM METHODS
1240  
1241 These methods let you work with the forms on a page. The idea is
1242 to choose a form that you'll later work with using the field methods
1243 below.
1244  
1245 =head2 $mech->forms
1246  
1247 Lists all the forms on the current page. Each form is an L<HTML::Form>
1248 object. In list context, returns a list of all forms. In scalar
1249 context, returns an array reference of all forms.
1250  
1251 =cut
1252  
1253 sub forms {
1254 11 ▶ my $self = shift;
Subroutine forms: called CC=3 SCAR=11.0
Pod documented
1255  
1256 11 ▶ $self->_extract_forms() unless $self->{forms};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"forms"} 8 3 11
1257  
1258 11 ▶ return @{$self->{forms}} if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 10 11
1259 10 return $self->{forms};
1260 }
1261  
1262 sub current_form {
1263 30 ▶ my $self = shift;
Subroutine current_form: called CC=2 SCAR=6.9
Pod documented
1264  
1265 30 ▶ if ( !$self->{current_form} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"current_form"}) 2 28 30
1266 2 $self->form_number(1);
1267 }
1268  
1269 30 return $self->{current_form};
1270 }
1271  
1272 =head2 $mech->form_number($number)
1273  
1274 Selects the I<number>th form on the page as the target for subsequent
1275 calls to C<L</field()>> and C<L</click()>>. Also returns the form that was
1276 selected.
1277  
1278 If it is found, the form is returned as an L<HTML::Form> object and set internally
1279 for later use with Mech's form methods such as C<L</field()>> and C<L</click()>>.
1280  
1281 Emits a warning and returns undef if no form is found.
1282  
1283 The first form is number 1, not zero.
1284  
1285 =cut
1286  
1287 sub form_number {
1288 7 ▶ my ($self, $form) = @_;
Subroutine form_number: called CC=2 SCAR=7.2
Pod documented
1289 # XXX Should we die if no $form is defined? Same question for form_name()
1290  
1291 7 my $forms = $self->forms;
1292 7 ▶ if ( $forms->[$form-1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$forms[$form - 1]) 7 0 7
1293 7 $self->{current_form} = $forms->[$form-1];
1294 7 return $self->{current_form};
1295 }
1296  
1297 0 return;
1298 }
1299  
1300 =head2 $mech->form_name( $name )
1301  
1302 Selects a form by name. If there is more than one form on the page
1303 with that name, then the first one is used, and a warning is
1304 generated.
1305  
1306 If it is found, the form is returned as an L<HTML::Form> object and
1307 set internally for later use with Mech's form methods such as
1308 C<L</field()>> and C<L</click()>>.
1309  
1310 Returns undef if no form is found.
1311  
1312 =cut
1313  
1314 sub form_name {
1315 0 ▶ my ($self, $form) = @_;
Subroutine form_name: not called CC=4 SCAR=30.0
Pod documented
1316  
1317 0 my $temp;
1318 0 ▶ my @matches = grep {defined($temp = $_->attr('name')) and ($temp eq $form) } $self->forms;
Branch: 1 branch
BranchTrueFalseTotal
defined($temp = $_->attr("name")) and $temp eq $form 0 0 0
1319  
1320 0 my $nmatches = @matches;
1321 0 ▶ if ( $nmatches > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nmatches > 0) 0 0 0
1322 0 ▶ if ( $nmatches > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nmatches > 1) 0 0 0
1323 0 $self->warn( "There are $nmatches forms named $form. The first one was used." )
1324 }
1325 0 return $self->{current_form} = $matches[0];
1326 }
1327  
1328 0 return;
1329 }
1330  
1331 =head2 $mech->form_id( $name )
1332  
1333 Selects a form by ID. If there is more than one form on the page
1334 with that ID, then the first one is used, and a warning is generated.
1335  
1336 If it is found, the form is returned as an L<HTML::Form> object and
1337 set internally for later use with Mech's form methods such as
1338 C<L</field()>> and C<L</click()>>.
1339  
1340 Returns undef if no form is found.
1341  
1342 =cut
1343  
1344 sub form_id {
1345 0 ▶ my ($self, $formid) = @_;
Subroutine form_id: not called CC=4 SCAR=30.0
Pod documented
1346  
1347 0 my $temp;
1348 0 ▶ my @matches = grep { defined($temp = $_->attr('id')) and ($temp eq $formid) } $self->forms;
Branch: 1 branch
BranchTrueFalseTotal
defined($temp = $_->attr("id")) and $temp eq $formid 0 0 0
1349 0 ▶ if ( @matches ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@matches) { } 0 0 0
1350 0 ▶ $self->warn( 'There are ', scalar @matches, " forms with ID $formid. The first one was used." )
Branch: 1 branch
BranchTrueFalseTotal
if @matches > 1 0 0 0
1351 if @matches > 1;
1352 0 return $self->{current_form} = $matches[0];
1353 }
1354 else {
1355 0 $self->warn( qq{ There is no form with ID "$formid"} );
1356 0 return undef;
1357 }
1358 }
1359  
1360  
1361 =head2 $mech->form_with_fields( @fields )
1362  
1363 Selects a form by passing in a list of field names it must contain. If there
1364 is more than one form on the page with that matches, then the first one is used,
1365 and a warning is generated.
1366  
1367 If it is found, the form is returned as an L<HTML::Form> object and set internally
1368 for later used with Mech's form methods such as C<L</field()>> and C<L</click()>>.
1369  
1370 Returns undef if no form is found.
1371  
1372 Note that this functionality requires libwww-perl 5.69 or higher.
1373  
1374 =cut
1375  
1376 sub form_with_fields {
1377 4 ▶ my ($self, @fields) = @_;
Subroutine form_with_fields: called CC=7 SCAR=19.6
Pod documented
1378 4 ▶ die 'no fields provided' unless scalar @fields;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @fields 1 3 4
1379  
1380 3 my @matches;
1381 3 FORMS: for my $form (@{ $self->forms }) {
1382 6 my @fields_in_form = $form->param();
1383 6 for my $field (@fields) {
1384 10 ▶ next FORMS unless grep { $_ eq $field } @fields_in_form;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $field;} @fields_in_form 2 8 10
1385 }
1386 4 push @matches, $form;
1387 }
1388  
1389 3 my $nmatches = @matches;
1390 3 ▶ if ( $nmatches > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nmatches > 0) { } 3 0 3
1391 3 ▶ if ( $nmatches > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nmatches > 1) 1 2 3
1392 1 $self->warn( "There are $nmatches forms with the named fields. The first one was used." )
1393 }
1394 3 return $self->{current_form} = $matches[0];
1395 }
1396 else {
1397 0 $self->warn( qq{There is no form with the requested fields} );
1398 0 return undef;
1399 }
1400 }
1401  
1402 =head1 FIELD METHODS
1403  
1404 These methods allow you to set the values of fields in a given form.
1405  
1406 =head2 $mech->field( $name, $value, $number )
1407  
1408 =head2 $mech->field( $name, \@values, $number )
1409  
1410 Given the name of a field, set its value to the value specified.
1411 This applies to the current form (as set by the L</form_name()> or
1412 L</form_number()> method or defaulting to the first form on the
1413 page).
1414  
1415 The optional I<$number> parameter is used to distinguish between two fields
1416 with the same name. The fields are numbered from 1.
1417  
1418 =cut
1419  
1420 sub field {
1421 2 ▶ my ($self, $name, $value, $number) = @_;
Subroutine field: called CC=4 SCAR=15.5
Pod documented
1422 2 ▶ $number ||= 1;
Condition50%1/2
$number ||= 1
l!l
02
MC/DC0%0/1
$number ||= 1
$number
Truth table50%1/2
A
A= $number
Aresult
11
00
1423  
1424 2 my $form = $self->current_form();
1425 2 ▶ if ($number > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($number > 1) { } 0 2 2
1426 0 $form->find_input($name, undef, $number)->value($value);
1427 }
1428 else {
1429 2 ▶ if ( ref($value) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 0 2 2
1430 0 $form->param($name, $value);
1431 }
1432 else {
1433 2 $form->value($name => $value);
1434 }
1435 }
1436 }
1437  
1438 =head2 $mech->select($name, $value)
1439  
1440 =head2 $mech->select($name, \@values)
1441  
1442 Given the name of a C<select> field, set its value to the value
1443 specified. If the field is not C<< <select multiple> >> and the
1444 C<$value> is an array, only the B<first> value will be set. [Note:
1445 the documentation previously claimed that only the last value would
1446 be set, but this was incorrect.] Passing C<$value> as a hash with
1447 an C<n> key selects an item by number (e.g.
1448 C<< {n => 3} >> or C<< {n => [2,4]} >>).
1449 The numbering starts at 1. This applies to the current form.
1450  
1451 If you have a field with C<< <select multiple> >> and you pass a single
1452 C<$value>, then C<$value> will be added to the list of fields selected,
1453 without clearing the others. However, if you pass an array reference,
1454 then all previously selected values will be cleared.
1455  
1456 Returns true on successfully setting the value. On failure, returns
1457 false and calls C<< $self>warn() >> with an error message.
1458  
1459 =cut
1460  
1461 sub select {
1462 9 ▶ my ($self, $name, $value) = @_;
Subroutine select: called CC=15 SCAR=29.1
Pod documented
1463  
1464 9 my $form = $self->current_form();
1465  
1466 9 my $input = $form->find_input($name);
1467 9 ▶ if (!$input) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($input) 1 8 9
1468 1 $self->warn( qq{Input "$name" not found} );
1469 1 return;
1470 }
1471  
1472 8 ▶ if ($input->type ne 'option') {
Branch: 1 branch
BranchTrueFalseTotal
if ($input->type ne "option") 0 8 8
1473 0 $self->warn( qq{Input "$name" is not type "select"} );
1474 0 return;
1475 }
1476  
1477 # For $mech->select($name, {n => 3}) or $mech->select($name, {n => [2,4]}),
1478 # transform the 'n' number(s) into value(s) and put it in $value.
1479 8 ▶ if (ref($value) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq "HASH") 4 4 8
1480 4 for (keys %$value) {
1481 4 ▶ $self->warn(qq{Unknown select value parameter "$_"})
Branch: 1 branch
BranchTrueFalseTotal
unless $_ eq "n" 0 4 4
1482 unless $_ eq 'n';
1483 }
1484  
1485 4 ▶ if (defined($value->{n})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value->{'n'}) { } 4 0 4
1486 4 my @inputs = $form->find_input($name, 'option');
1487 4 my @values = ();
1488 # distinguish between multiple and non-multiple selects
1489 # (see INPUTS section of `perldoc HTML::Form`)
1490 4 ▶ if (@inputs == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@inputs == 1) { } 2 2 4
1491 2 @values = $inputs[0]->possible_values();
1492 }
1493 else {
1494 2 foreach my $input (@inputs) {
1495 8 my @possible = $input->possible_values();
1496 8 push @values, pop @possible;
1497 }
1498 }
1499  
1500 4 my $n = $value->{n};
1501 4 ▶ if (ref($n) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $n eq 'ARRAY') { } 2 2 4
elsif (not ref $n and $n =~ /^\d+$/) { } 2 0 2
1502 2 $value = [];
1503 2 for (@$n) {
1504 4 ▶ unless (/^\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/^\d+$/) 0 4 4
1505 0 $self->warn(qq{"n" value "$_" is not a positive integer});
1506 0 return;
1507 }
1508 4 push @$value, $values[$_ - 1]; # might be undef
1509 }
1510 }
1511 ▶ elsif (!ref($n) && $n =~ /^\d+$/) {
Condition33%1/3
not ref $n and $n =~ /^\d+$/
!ll&&!rl&&r
002
MC/DC0%0/2
not ref $n and $n =~ /^\d+$/
not ref $n $n =~ /^\d+$/
Truth table33%1/3
not(A) and B
A= not ref $nB= $n =~ /^\d+$/
ABresult
0X0
100
111
1512 2 $value = $values[$n - 1]; # might be undef
1513 }
1514 else {
1515 0 $self->warn('"n" value is not a positive integer or an array ref');
1516 0 return;
1517 }
1518 }
1519 else {
1520 0 $self->warn('Hash value is invalid');
1521 0 return;
1522 }
1523 } # hashref
1524  
1525 8 ▶ if (ref($value) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq "ARRAY") 4 4 8
1526 4 $form->param($name, $value);
1527 4 return 1;
1528 }
1529  
1530 4 $form->value($name => $value);
1531 4 return 1;
1532 }
1533  
1534 =head2 $mech->set_fields( $name => $value ... )
1535  
1536 This method sets multiple fields of the current form. It takes a list
1537 of field name and value pairs. If there is more than one field with
1538 the same name, the first one found is set. If you want to select which
1539 of the duplicate field to set, use a value which is an anonymous array
1540 which has the field value and its number as the 2 elements.
1541  
1542 # set the second foo field
1543 $mech->set_fields( $name => [ 'foo', 2 ] );
1544  
1545 The fields are numbered from 1.
1546  
1547 This applies to the current form.
1548  
1549 =cut
1550  
1551 sub set_fields {
1552 1 ▶ my $self = shift;
Subroutine set_fields: called CC=4 SCAR=14.3
Pod documented
1553 1 my %fields = @_;
1554  
1555 1 ▶ my $form = $self->current_form or $self->die( 'No form defined' );
Branch: 1 branch
BranchTrueFalseTotal
my $form = $self->current_form or $self->die("No form defined") 0 1 1
1556  
1557 1 ▶ while ( my ( $field, $value ) = each %fields ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %fields) 2 1 3
1558 2 ▶ if ( ref $value eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 0 2 2
1559 0 $form->find_input( $field, undef,
1560 $value->[1])->value($value->[0] );
1561 }
1562 else {
1563 2 $form->value($field => $value);
1564 }
1565 } # while
1566 } # set_fields()
1567  
1568 =head2 $mech->set_visible( @criteria )
1569  
1570 This method sets fields of the current form without having to know
1571 their names. So if you have a login screen that wants a username and
1572 password, you do not have to fetch the form and inspect the source (or
1573 use the F<mech-dump> utility, installed with WWW::Mechanize) to see
1574 what the field names are; you can just say
1575  
1576 $mech->set_visible( $username, $password );
1577  
1578 and the first and second fields will be set accordingly. The method
1579 is called set_I<visible> because it acts only on visible fields;
1580 hidden form inputs are not considered. The order of the fields is
1581 the order in which they appear in the HTML source which is nearly
1582 always the order anyone viewing the page would think they are in,
1583 but some creative work with tables could change that; caveat user.
1584  
1585 Each element in C<@criteria> is either a field value or a field
1586 specifier. A field value is a scalar. A field specifier allows
1587 you to specify the I<type> of input field you want to set and is
1588 denoted with an arrayref containing two elements. So you could
1589 specify the first radio button with
1590  
1591 $mech->set_visible( [ radio => 'KCRW' ] );
1592  
1593 Field values and specifiers can be intermixed, hence
1594  
1595 $mech->set_visible( 'fred', 'secret', [ option => 'Checking' ] );
1596  
1597 would set the first two fields to "fred" and "secret", and the I<next>
1598 C<OPTION> menu field to "Checking".
1599  
1600 The possible field specifier types are: "text", "password", "hidden",
1601 "textarea", "file", "image", "submit", "radio", "checkbox" and "option".
1602  
1603 C<set_visible> returns the number of values set.
1604  
1605 =cut
1606  
1607 sub set_visible {
1608 2 ▶ my $self = shift;
Subroutine set_visible: called CC=8 SCAR=21.0
Pod documented
1609  
1610 2 my $form = $self->current_form;
1611 2 my @inputs = $form->inputs;
1612  
1613 2 my $num_set = 0;
1614 2 for my $value ( @_ ) {
1615 # Handle type/value pairs an arrayref
1616 4 ▶ if ( ref $value eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 1 3 4
1617 1 my ( $type, $value ) = @$value;
1618 1 ▶ while ( my $input = shift @inputs ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $input = shift @inputs) 3 0 3
1619 3 ▶ next if $input->type eq 'hidden';
Branch: 1 branch
BranchTrueFalseTotal
if $input->type eq "hidden" 0 3 3
1620 3 ▶ if ( $input->type eq $type ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input->type eq $type) 1 2 3
1621 1 $input->value( $value );
1622 1 $num_set++;
1623 1 last;
1624 }
1625 } # while
1626 }
1627 # by default, it's a value
1628 else {
1629 3 ▶ while ( my $input = shift @inputs ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $input = shift @inputs) 3 0 3
1630 3 ▶ next if $input->type eq 'hidden';
Branch: 1 branch
BranchTrueFalseTotal
if $input->type eq "hidden" 0 3 3
1631 3 $input->value( $value );
1632 3 $num_set++;
1633 3 last;
1634 } # while
1635 }
1636 } # for
1637  
1638 2 return $num_set;
1639 } # set_visible()
1640  
1641 =head2 $mech->tick( $name, $value [, $set] )
1642  
1643 "Ticks" the first checkbox that has both the name and value associated
1644 with it on the current form. Dies if there is no named check box for
1645 that value. Passing in a false value as the third optional argument
1646 will cause the checkbox to be unticked.
1647  
1648 =cut
1649  
1650 sub tick {
1651 1 ▶ my $self = shift;
Subroutine tick: called CC=7 SCAR=31.6
Pod documented
1652 1 my $name = shift;
1653 1 my $value = shift;
1654 1 ▶ my $set = @_ ? shift : 1; # default to 1 if not passed
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 1 1
1655  
1656 # loop though all the inputs
1657 1 my $index = 0;
1658 1 ▶ while ( my $input = $self->current_form->find_input( $name, 'checkbox', $index ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $input = $self->current_form->find_input($name, "checkbox", $index)) 0 0 0
1659 # Can't guarantee that the first element will be undef and the second
1660 # element will be the right name
1661 0 foreach my $val ($input->possible_values()) {
1662 0 ▶ next unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 0 0
1663 0 ▶ if ($val eq $value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val eq $value) 0 0 0
1664 0 ▶ $input->value($set ? $value : undef);
Branch: 1 branch
BranchTrueFalseTotal
$set ? : 0 0 0
1665 0 return;
1666 }
1667 }
1668  
1669 # move onto the next input
1670 0 $index++;
1671 } # while
1672  
1673 # got self far? Didn't find anything
1674 0 $self->warn( qq{No checkbox "$name" for value "$value" in form} );
1675 } # tick()
1676  
1677 =head2 $mech->untick($name, $value)
1678  
1679 Causes the checkbox to be unticked. Shorthand for
1680 C<tick($name,$value,undef)>
1681  
1682 =cut
1683  
1684 sub untick {
1685 0 ▶ shift->tick(shift,shift,undef);
Subroutine untick: not called CC=1 SCAR=6.9
Pod documented
1686 }
1687  
1688 =head2 $mech->value( $name [, $number] )
1689  
1690 Given the name of a field, return its value. This applies to the current
1691 form.
1692  
1693 The optional I<$number> parameter is used to distinguish between two fields
1694 with the same name. The fields are numbered from 1.
1695  
1696 If the field is of type file (file upload field), the value is always
1697 cleared to prevent remote sites from downloading your local files.
1698 To upload a file, specify its file name explicitly.
1699  
1700 =cut
1701  
1702 sub value {
1703 5 ▶ my $self = shift;
Subroutine value: called CC=3 SCAR=11.0
Pod documented
1704 5 my $name = shift;
1705 5 ▶ my $number = shift || 1;
Condition100%2/2
shift() || 1
l!l
14
MC/DC100%1/1
shift() || 1
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
1706  
1707 5 my $form = $self->current_form;
1708 5 ▶ if ( $number > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($number > 1) { } 1 4 5
1709 1 return $form->find_input( $name, undef, $number )->value();
1710 }
1711 else {
1712 4 return $form->value( $name );
1713 }
1714 } # value
1715  
1716 =head2 $mech->click( $button [, $x, $y] )
1717  
1718 Has the effect of clicking a button on the current form. The first
1719 argument is the name of the button to be clicked. The second and
1720 third arguments (optional) allow you to specify the (x,y) coordinates
1721 of the click.
1722  
1723 If there is only one button on the form, C<< $mech->click() >> with
1724 no arguments simply clicks that one button.
1725  
1726 Returns an L<HTTP::Response> object.
1727  
1728 =cut
1729  
1730 sub click {
1731 0 ▶ my ($self, $button, $x, $y) = @_;
Subroutine click: not called CC=3 SCAR=24.8
Pod documented
1732 0 ▶ for ($x, $y) { $_ = 1 unless defined; }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 0 0
1733 0 my $request = $self->current_form->click($button, $x, $y);
1734 0 return $self->request( $request );
1735 }
1736  
1737 =head2 $mech->click_button( ... )
1738  
1739 Has the effect of clicking a button on the current form by specifying
1740 its name, value, or index. Its arguments are a list of key/value
1741 pairs. Only one of name, number, input or value must be specified in
1742 the keys.
1743  
1744 =over 4
1745  
1746 =item * C<< name => name >>
1747  
1748 Clicks the button named I<name> in the current form.
1749  
1750 =item * C<< number => n >>
1751  
1752 Clicks the I<n>th button in the current form. Numbering starts at 1.
1753  
1754 =item * C<< value => value >>
1755  
1756 Clicks the button with the value I<value> in the current form.
1757  
1758 =item * C<< input => $inputobject >>
1759  
1760 Clicks on the button referenced by $inputobject, an instance of
1761 L<HTML::Form::SubmitInput> obtained e.g. from
1762  
1763 $mech->current_form()->find_input( undef, 'submit' )
1764  
1765 $inputobject must belong to the current form.
1766  
1767 =item * C<< x => x >>
1768  
1769 =item * C<< y => y >>
1770  
1771 These arguments (optional) allow you to specify the (x,y) coordinates
1772 of the click.
1773  
1774 =back
1775  
1776 =cut
1777  
1778 sub click_button {
1779 0 ▶ my $self = shift;
Subroutine click_button: not called CC=13 SCAR=52.0
Pod documented
1780 0 my %args = @_;
1781  
1782 0 for ( keys %args ) {
1783 0 ▶ if ( !/^(number|name|value|input|x|y)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/^(number|name|value|input|x|y)$/) 0 0 0
1784 0 $self->warn( qq{Unknown click_button parameter "$_"} );
1785 }
1786 }
1787  
1788 0 for ($args{x}, $args{y}) {
1789 0 ▶ $_ = 1 unless defined;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 0 0
1790 }
1791  
1792 0 ▶ my $form = $self->current_form or $self->die( 'click_button: No form has been selected' );
Branch: 1 branch
BranchTrueFalseTotal
my $form = $self->current_form or $self->die("click_button: No form has been selected") 0 0 0
1793  
1794 0 my $request;
1795 0 ▶ if ( $args{name} ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($args{'name'}) { } 0 0 0
elsif ($args{'number'}) { } 0 0 0
elsif ($args{'input'}) { } 0 0 0
elsif ($args{'value'}) { } 0 0 0
1796 0 $request = $form->click( $args{name}, $args{x}, $args{y} );
1797 }
1798 elsif ( $args{number} ) {
1799 0 my $input = $form->find_input( undef, 'submit', $args{number} );
1800 0 $request = $input->click( $form, $args{x}, $args{y} );
1801 }
1802 elsif ( $args{input} ) {
1803 0 $request = $args{input}->click( $form, $args{x}, $args{y} );
1804 }
1805 elsif ( $args{value} ) {
1806 0 my $i = 1;
1807 0 ▶ while ( my $input = $form->find_input(undef, 'submit', $i) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $input = $form->find_input(undef, "submit", $i)) 0 0 0
1808 0 ▶ if ( $args{value} && ($args{value} eq $input->value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"value"} and $args{"value"} eq $input->value) 0 0 0
Condition0%0/3
$args{"value"} and $args{"value"} eq $input->value
!ll&&!rl&&r
000
MC/DC0%0/2
$args{"value"} and $args{"value"} eq $input->value
$args{"value"} $args{"value"} eq $input->value
Truth table0%0/3
A and B
A= $args{"value"}B= $args{"value"} eq $input->value
ABresult
0X0
100
111
1809 0 $request = $input->click( $form, $args{x}, $args{y} );
1810 0 last;
1811 }
1812 0 $i++;
1813 } # while
1814 } # $args{value}
1815  
1816 0 return $self->request( $request );
1817 }
1818  
1819 =head2 $mech->submit()
1820  
1821 Submits the page, without specifying a button to click. Actually,
1822 no button is clicked at all.
1823  
1824 Returns an L<HTTP::Response> object.
1825  
1826 This used to be a synonym for C<< $mech->click( 'submit' ) >>, but is no
1827 longer so.
1828  
1829 =cut
1830  
1831 sub submit {
1832 1 ▶ my $self = shift;
Subroutine submit: called CC=1 SCAR=0.0
Pod documented
1833  
1834 1 my $request = $self->current_form->make_request;
1835 1 return $self->request( $request );
1836 }
1837  
1838 =head2 $mech->submit_form( ... )
1839  
1840 This method lets you select a form from the previously fetched page,
1841 fill in its fields, and submit it. It combines the form_number/form_name,
1842 set_fields and click methods into one higher level call. Its arguments
1843 are a list of key/value pairs, all of which are optional.
1844  
1845 =over 4
1846  
1847 =item * C<< fields => \%fields >>
1848  
1849 Specifies the fields to be filled in the current form.
1850  
1851 =item * C<< with_fields => \%fields >>
1852  
1853 Probably all you need for the common case. It combines a smart form selector
1854 and data setting in one operation. It selects the first form that contains all
1855 fields mentioned in C<\%fields>. This is nice because you don't need to know
1856 the name or number of the form to do this.
1857  
1858 (calls C<L</form_with_fields()>> and C<L</set_fields()>>).
1859  
1860 If you choose this, the form_number, form_name, form_id and fields options will be ignored.
1861  
1862 =item * C<< form_number => n >>
1863  
1864 Selects the I<n>th form (calls C<L</form_number()>>). If this parm is not
1865 specified, the currently-selected form is used.
1866  
1867 =item * C<< form_name => name >>
1868  
1869 Selects the form named I<name> (calls C<L</form_name()>>)
1870  
1871 =item * C<< form_id => ID >>
1872  
1873 Selects the form with ID I<ID> (calls C<L</form_id()>>)
1874  
1875 =item * C<< button => button >>
1876  
1877 Clicks on button I<button> (calls C<L</click()>>)
1878  
1879 =item * C<< x => x, y => y >>
1880  
1881 Sets the x or y values for C<L</click()>>
1882  
1883 =back
1884  
1885 If no form is selected, the first form found is used.
1886  
1887 If I<button> is not passed, then the C<L</submit()>> method is used instead.
1888  
1889 If you want to submit a file and get its content from a scalar rather
1890 than a file in the filesystem, you can use:
1891  
1892 $mech->submit_form(with_fields => { logfile => [ [ undef, 'whatever', Content => $content ], 1 ] } );
1893  
1894 Returns an L<HTTP::Response> object.
1895  
1896 =cut
1897  
1898 sub submit_form {
1899 1 ▶ my( $self, %args ) = @_;
Subroutine submit_form: called CC=19 SCAR=42.7
Pod documented
1900  
1901 1 for ( keys %args ) {
1902 1 ▶ if ( !/^(form_(number|name|fields|id)|(with_)?fields|button|x|y)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/^(form_(number|name|fields|id)|(with_)?fields|button|x|y)$/) 0 1 1
1903 # XXX Why not die here?
1904 0 $self->warn( qq{Unknown submit_form parameter "$_"} );
1905 }
1906 }
1907  
1908 1 my $fields;
1909 1 for (qw/with_fields fields/) {
1910 1 ▶ if ($args{$_}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{$_}) 1 0 1
1911 1 ▶ if ( ref $args{$_} eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args{$_} eq 'HASH') { } 1 0 1
1912 1 $fields = $args{$_};
1913 }
1914 else {
1915 0 die "$_ arg to submit_form must be a hashref";
1916 }
1917 1 last;
1918 }
1919 }
1920  
1921 1 ▶ if ( $args{with_fields} ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($args{'with_fields'}) { } 1 0 1
elsif (my $form_number = $args{'form_number'}) { } 0 0 0
elsif (my $form_name = $args{'form_name'}) { } 0 0 0
elsif (my $form_id = $args{'form_id'}) { } 0 0 0
1922 1 ▶ $fields || die q{must submit some 'fields' with with_fields};
Branch: 1 branch
BranchTrueFalseTotal
$fields or CORE::die "must submit some 'fields' with with_fields" 0 1 1
1923 1 ▶ $self->form_with_fields(keys %{$fields}) or die "There is no form with the requested fields";
Branch: 1 branch
BranchTrueFalseTotal
$self->form_with_fields(keys %{$fields;}) or CORE::die "There is no form with the requested fields" 0 1 1
1924 }
1925 elsif ( my $form_number = $args{form_number} ) {
1926 0 ▶ $self->form_number( $form_number ) or die "There is no form numbered $form_number";
Branch: 1 branch
BranchTrueFalseTotal
$self->form_number($form_number) or CORE::die "There is no form numbered $form_number" 0 0 0
1927 }
1928 elsif ( my $form_name = $args{form_name} ) {
1929 0 ▶ $self->form_name( $form_name ) or die qq{There is no form named "$form_name"};
Branch: 1 branch
BranchTrueFalseTotal
$self->form_name($form_name) or CORE::die qq[There is no form named "$form_name"] 0 0 0
1930 }
1931 elsif ( my $form_id = $args{form_id} ) {
1932 0 ▶ $self->form_id( $form_id ) or die qq{There is no form with ID "$form_id"};
Branch: 1 branch
BranchTrueFalseTotal
$self->form_id($form_id) or CORE::die qq[There is no form with ID "$form_id"] 0 0 0
1933 }
1934 else {
1935 # No form selector was used.
1936 # Maybe a form was set separately, or we'll default to the first form.
1937 }
1938  
1939 1 ▶ $self->set_fields( %{$fields} ) if $fields;
Branch: 1 branch
BranchTrueFalseTotal
if $fields 1 0 1
1940  
1941 1 my $response;
1942 1 ▶ if ( $args{button} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'button'}) { } 0 1 1
1943 0 ▶ $response = $self->click( $args{button}, $args{x} || 0, $args{y} || 0 );
Condition0%0/4
$args{'x'} || 0
l!l
00
$args{'y'} || 0
l!l
00
MC/DC0%0/1
$args{'x'} || 0
$args{'x'}
MC/DC0%0/1
$args{'y'} || 0
$args{'y'}
Truth table0%0/2
A
A= $args{'x'}
Aresult
11
00
Truth table0%0/2
A
A= $args{'y'}
Aresult
11
00
1944 }
1945 else {
1946 1 $response = $self->submit();
1947 }
1948  
1949 1 return $response;
1950 }
1951  
1952 =head1 MISCELLANEOUS METHODS
1953  
1954 =head2 $mech->add_header( name => $value [, name => $value... ] )
1955  
1956 Sets HTTP headers for the agent to add or remove from the HTTP request.
1957  
1958 $mech->add_header( Encoding => 'text/klingon' );
1959  
1960 If a I<value> is C<undef>, then that header will be removed from any
1961 future requests. For example, to never send a Referer header:
1962  
1963 $mech->add_header( Referer => undef );
1964  
1965 If you want to delete a header, use C<delete_header>.
1966  
1967 Returns the number of name/value pairs added.
1968  
1969 B<NOTE>: This method was very different in WWW::Mechanize before 1.00.
1970 Back then, the headers were stored in a package hash, not as a member of
1971 the object instance. Calling C<add_header()> would modify the headers
1972 for every WWW::Mechanize object, even after your object no longer existed.
1973  
1974 =cut
1975  
1976 sub add_header {
1977 4 ▶ my $self = shift;
Subroutine add_header: called CC=2 SCAR=6.9
Pod documented
1978 4 my $npairs = 0;
1979  
1980 4 ▶ while ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 4 4 8
1981 4 my $key = shift;
1982 4 my $value = shift;
1983 4 ++$npairs;
1984  
1985 4 $self->{headers}{$key} = $value;
1986 }
1987  
1988 4 return $npairs;
1989 }
1990  
1991 =head2 $mech->delete_header( name [, name ... ] )
1992  
1993 Removes HTTP headers from the agent's list of special headers. For
1994 instance, you might need to do something like:
1995  
1996 # Don't send a Referer for this URL
1997 $mech->add_header( Referer => undef );
1998  
1999 # Get the URL
2000 $mech->get( $url );
2001  
2002 # Back to the default behavior
2003 $mech->delete_header( 'Referer' );
2004  
2005 =cut
2006  
2007 sub delete_header {
2008 0 ▶ my $self = shift;
Subroutine delete_header: not called CC=2 SCAR=17.9
Pod documented
2009  
2010 0 ▶ while ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
2011 0 my $key = shift;
2012  
2013 0 delete $self->{headers}{$key};
2014 }
2015  
2016 0 return;
2017 }
2018  
2019  
2020 =head2 $mech->quiet(true/false)
2021  
2022 Allows you to suppress warnings to the screen.
2023  
2024 $mech->quiet(0); # turns on warnings (the default)
2025 $mech->quiet(1); # turns off warnings
2026 $mech->quiet(); # returns the current quietness status
2027  
2028 =cut
2029  
2030 sub quiet {
2031 25 ▶ my $self = shift;
Subroutine quiet: called CC=2 SCAR=6.9
Pod documented
2032  
2033 25 ▶ $self->{quiet} = $_[0] if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 24 25
2034  
2035 25 return $self->{quiet};
2036 }
2037  
2038 =head2 $mech->stack_depth( $max_depth )
2039  
2040 Get or set the page stack depth. Use this if you're doing a lot of page
2041 scraping and running out of memory.
2042  
2043 A value of 0 means "no history at all." By default, the max stack depth
2044 is humongously large, effectively keeping all history.
2045  
2046 =cut
2047  
2048 sub stack_depth {
2049 26 ▶ my $self = shift;
Subroutine stack_depth: called CC=2 SCAR=7.1
Pod documented
2050 26 ▶ $self->{stack_depth} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 26 26
2051 26 return $self->{stack_depth};
2052 }
2053  
2054 =head2 $mech->save_content( $filename, %opts )
2055  
2056 Dumps the contents of C<< $mech->content >> into I<$filename>.
2057 I<$filename> will be overwritten. Dies if there are any errors.
2058  
2059 If the content type does not begin with "text/", then the content
2060 is saved in binary mode (i.e. C<binmode()> is set on the output
2061 filehandle).
2062  
2063 Additional arguments can be passed as I<key>/I<value> pairs:
2064  
2065 =over
2066  
2067 =item I<< $mech->save_content( $filename, binary => 1 ) >>
2068  
2069 Filehandle is set with C<binmode> to C<:raw> and contents are taken
2070 calling C<< $self->content(decoded_by_headers => 1) >>. Same as calling:
2071  
2072 $mech->save_content( $filename, binmode => ':raw',
2073 decoded_by_headers => 1 );
2074  
2075 This I<should> be the safest way to save contents verbatim.
2076  
2077 =item I<< $mech->save_content( $filename, binmode => $binmode ) >>
2078  
2079 Filehandle is set to binary mode. If C<$binmode> begins with ':', it is
2080 passed as a parameter to C<binmode>:
2081  
2082 binmode $fh, $binmode;
2083  
2084 otherwise the filehandle is set to binary mode if C<$binmode> is true:
2085  
2086 binmode $fh;
2087  
2088 =item I<all other arguments>
2089  
2090 are passed as-is to C<< $mech->content(%opts) >>. In particular,
2091 C<decoded_by_headers> might come handy if you want to revert the effect
2092 of line compression performed by the web server but without further
2093 interpreting the contents (e.g. decoding it according to the charset).
2094  
2095 =back
2096  
2097 =cut
2098  
2099 sub save_content {
2100 2 ▶ my $self = shift;
Subroutine save_content: called CC=10 SCAR=24.2
Pod documented
2101 2 my $filename = shift;
2102 2 my %opts = @_;
2103 2 ▶ if (delete $opts{binary}) {
Branch: 1 branch
BranchTrueFalseTotal
if (delete $opts{"binary"}) 1 1 2
2104 1 $opts{binmode} = ':raw';
2105 1 $opts{decoded_by_headers} = 1;
2106 }
2107  
2108 2 ▶ open( my $fh, '>', $filename ) or $self->die( "Unable to create $filename: $!" );
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $filename or $self->die("Unable to create ${filename}: $!") 0 2 2
2109 2 ▶ if ((my $binmode = delete($opts{binmode}) || '') || ($self->content_type() !~ m{^text/})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $binmode = delete $opts{"binmode"} || "" or not $self->content_type =~ m[^text/]) 1 1 2
Condition80%4/5
my $binmode = delete $opts{"binmode"} || "" or not $self->content_type =~ m[^text/]
l!l&&r!l&&!r
101
delete $opts{'binmode'} || ''
l!l
11
MC/DC50%1/2
my $binmode = delete $opts{"binmode"} || "" or not $self->content_type =~ m[^text/]
delete $opts{'binmode'} not $self->content_type =~ m[^text/]
Truth table66%2/3
A or not(B)
A= delete $opts{'binmode'}B= not $self->content_type =~ m[^text/]
ABresult
1X1
011
000
2110 1 ▶ if (length($binmode) && (substr($binmode, 0, 1) eq ':')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $binmode and substr($binmode, 0, 1) eq ':') { } 1 0 1
Condition33%1/3
length $binmode and substr($binmode, 0, 1) eq ":"
!ll&&!rl&&r
001
MC/DC0%0/2
length $binmode and substr($binmode, 0, 1) eq ":"
length $binmode substr($binmode, 0, 1) eq ":"
Truth table33%1/3
A and B
A= length $binmodeB= substr($binmode, 0, 1) eq ":"
ABresult
0X0
100
111
2111 1 binmode $fh, $binmode;
2112 }
2113 else {
2114 0 binmode $fh;
2115 }
2116 }
2117 2 ▶ print {$fh} $self->content(%opts) or $self->die( "Unable to write to $filename: $!" );
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $self->content(%opts) or $self->die("Unable to write to ${filename}: $!") 0 2 2
2118 2 ▶ close $fh or $self->die( "Unable to close $filename: $!" );
Branch: 1 branch
BranchTrueFalseTotal
close $fh or $self->die("Unable to close ${filename}: $!") 0 2 2
2119  
2120 2 return;
2121 }
2122  
2123  
2124 =head2 $mech->dump_headers( [$fh] )
2125  
2126 Prints a dump of the HTTP response headers for the most recent
2127 response. If I<$fh> is not specified or is undef, it dumps to
2128 STDOUT.
2129  
2130 Unlike the rest of the dump_* methods, $fh can be a scalar. It
2131 will be used as a file name.
2132  
2133 =cut
2134  
2135 sub _get_fh_default_stdout {
2136 2 ▶ my $self = shift;
Subroutine _get_fh_default_stdout: called CC=5 SCAR=17.0
2137 2 ▶ my $p = shift || '';
Condition50%1/2
shift() || ''
l!l
20
MC/DC0%0/1
shift() || ''
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
2138 2 ▶ if ( !$p ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $p) { } 0 2 2
elsif (not ref $p) { } 1 1 2
2139 0 return \*STDOUT;
2140 } elsif ( !ref($p) ) {
2141 1 ▶ open my $fh, '>', $p or $self->die( "Unable to write to $p: $!" );;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $p or $self->die("Unable to write to ${p}: $!") 0 1 1
2142 1 return $fh;
2143 } else {
2144 1 return $p;
2145 }
2146 }
2147  
2148 sub dump_headers {
2149 2 ▶ my $self = shift;
Subroutine dump_headers: called CC=1 SCAR=0.0
Pod documented
2150 2 my $fh = $self->_get_fh_default_stdout(shift);
2151  
2152 2 print {$fh} $self->response->headers_as_string;
2153  
2154 2 return;
2155 }
2156  
2157  
2158 =head2 $mech->dump_links( [[$fh], $absolute] )
2159  
2160 Prints a dump of the links on the current page to I<$fh>. If I<$fh>
2161 is not specified or is undef, it dumps to STDOUT.
2162  
2163 If I<$absolute> is true, links displayed are absolute, not relative.
2164  
2165 =cut
2166  
2167 sub dump_links {
2168 0 ▶ my $self = shift;
Subroutine dump_links: not called CC=5 SCAR=34.0
Pod documented
2169 0 ▶ my $fh = shift || \*STDOUT;
Condition0%0/2
shift() || \*STDOUT
l!l
00
MC/DC0%0/1
shift() || \*STDOUT
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
2170 0 my $absolute = shift;
2171  
2172 0 for my $link ( $self->links ) {
2173 0 ▶ my $url = $absolute ? $link->url_abs : $link->url;
Branch: 1 branch
BranchTrueFalseTotal
$absolute ? : 0 0 0
2174 0 ▶ $url = '' if not defined $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url 0 0 0
2175 0 print {$fh} $url, "\n";
2176 }
2177 0 return;
2178 }
2179  
2180 =head2 $mech->dump_images( [[$fh], $absolute] )
2181  
2182 Prints a dump of the images on the current page to I<$fh>. If I<$fh>
2183 is not specified or is undef, it dumps to STDOUT.
2184  
2185 If I<$absolute> is true, links displayed are absolute, not relative.
2186  
2187 =cut
2188  
2189 sub dump_images {
2190 0 ▶ my $self = shift;
Subroutine dump_images: not called CC=5 SCAR=34.0
Pod documented
2191 0 ▶ my $fh = shift || \*STDOUT;
Condition0%0/2
shift() || \*STDOUT
l!l
00
MC/DC0%0/1
shift() || \*STDOUT
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
2192 0 my $absolute = shift;
2193  
2194 0 for my $image ( $self->images ) {
2195 0 ▶ my $url = $absolute ? $image->url_abs : $image->url;
Branch: 1 branch
BranchTrueFalseTotal
$absolute ? : 0 0 0
2196 0 ▶ $url = '' if not defined $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url 0 0 0
2197 0 print {$fh} $url, "\n";
2198 }
2199 0 return;
2200 }
2201  
2202 =head2 $mech->dump_forms( [$fh] )
2203  
2204 Prints a dump of the forms on the current page to I<$fh>. If I<$fh>
2205 is not specified or is undef, it dumps to STDOUT.
2206  
2207 =cut
2208  
2209 sub dump_forms {
2210 1 ▶ my $self = shift;
Subroutine dump_forms: called CC=3 SCAR=11.0
Pod documented
2211 1 ▶ my $fh = shift || \*STDOUT;
Condition50%1/2
shift() || \*STDOUT
l!l
01
MC/DC0%0/1
shift() || \*STDOUT
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
2212  
2213 1 for my $form ( $self->forms ) {
2214 1 print {$fh} $form->dump, "\n";
2215 }
2216 1 return;
2217 }
2218  
2219 =head2 $mech->dump_text( [$fh] )
2220  
2221 Prints a dump of the text on the current page to I<$fh>. If I<$fh>
2222 is not specified or is undef, it dumps to STDOUT.
2223  
2224 =cut
2225  
2226 sub dump_text {
2227 0 ▶ my $self = shift;
Subroutine dump_text: not called CC=2 SCAR=17.9
Pod documented
2228 0 ▶ my $fh = shift || \*STDOUT;
Condition0%0/2
shift() || \*STDOUT
l!l
00
MC/DC0%0/1
shift() || \*STDOUT
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
2229 0 my $absolute = shift;
2230  
2231 0 print {$fh} $self->text, "\n";
2232  
2233 0 return;
2234 }
2235  
2236  
2237 =head1 OVERRIDDEN LWP::UserAgent METHODS
2238  
2239 =head2 $mech->clone()
2240  
2241 Clone the mech object. The clone will be using the same cookie jar
2242 as the original mech.
2243  
2244 =cut
2245  
2246 sub clone {
2247 2 ▶ my $self = shift;
Subroutine clone: called CC=1 SCAR=0.0
Pod documented
2248 2 my $clone = $self->SUPER::clone();
2249  
2250 2 $clone->cookie_jar( $self->cookie_jar );
2251  
2252 2 return $clone;
2253 }
2254  
2255  
2256 =head2 $mech->redirect_ok()
2257  
2258 An overloaded version of C<redirect_ok()> in L<LWP::UserAgent>.
2259 This method is used to determine whether a redirection in the request
2260 should be followed.
2261  
2262 Note that WWW::Mechanize's constructor pushes POST on to the agent's
2263 C<requests_redirectable> list.
2264  
2265 =cut
2266  
2267 sub redirect_ok {
2268 0 ▶ my $self = shift;
Subroutine redirect_ok: not called CC=2 SCAR=17.9
Pod documented
2269 0 my $prospective_request = shift;
2270 0 my $response = shift;
2271  
2272 0 my $ok = $self->SUPER::redirect_ok( $prospective_request, $response );
2273 0 ▶ if ( $ok ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) 0 0 0
2274 0 $self->{redirected_uri} = $prospective_request->uri;
2275 }
2276  
2277 0 return $ok;
2278 }
2279  
2280  
2281 =head2 $mech->request( $request [, $arg [, $size]])
2282  
2283 Overloaded version of C<request()> in L<LWP::UserAgent>. Performs
2284 the actual request. Normally, if you're using WWW::Mechanize, it's
2285 because you don't want to deal with this level of stuff anyway.
2286  
2287 Note that C<$request> will be modified.
2288  
2289 Returns an L<HTTP::Response> object.
2290  
2291 =cut
2292  
2293 sub request {
2294 36 ▶ my $self = shift;
Subroutine request: called CC=3 SCAR=11.2
Pod documented
2295 36 my $request = shift;
2296  
2297 36 $request = $self->_modify_request( $request );
2298  
2299 36 ▶ if ( $request->method eq 'GET' || $request->method eq 'POST' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->method eq "GET" or $request->method eq "POST") 36 0 36
Condition66%2/3
$request->method eq "GET" or $request->method eq "POST"
l!l&&r!l&&!r
3510
MC/DC0%0/2
$request->method eq "GET" or $request->method eq "POST"
$request->method eq "GET" $request->method eq "POST"
Truth table66%2/3
A or B
A= $request->method eq "GET"B= $request->method eq "POST"
ABresult
1X1
011
000
2300 36 $self->_push_page_stack();
2301 }
2302  
2303 36 return $self->_update_page($request, $self->_make_request( $request, @_ ));
2304 }
2305  
2306 =head2 $mech->update_html( $html )
2307  
2308 Allows you to replace the HTML that the mech has found. Updates the
2309 forms and links parse-trees that the mech uses internally.
2310  
2311 Say you have a page that you know has malformed output, and you want to
2312 update it so the links come out correctly:
2313  
2314 my $html = $mech->content;
2315 $html =~ s[</option>.{0,3}</td>][</option></select></td>]isg;
2316 $mech->update_html( $html );
2317  
2318 This method is also used internally by the mech itself to update its
2319 own HTML content when loading a page. This means that if you would
2320 like to I<systematically> perform the above HTML substitution, you
2321 would overload I<update_html> in a subclass thusly:
2322  
2323 package MyMech;
2324 use base 'WWW::Mechanize';
2325  
2326 sub update_html {
2327 my ($self, $html) = @_;
2328 $html =~ s[</option>.{0,3}</td>][</option></select></td>]isg;
2329 $self->WWW::Mechanize::update_html( $html );
2330 }
2331  
2332 If you do this, then the mech will use the tidied-up HTML instead of
2333 the original both when parsing for its own needs, and for returning to
2334 you through L</content>.
2335  
2336 Overloading this method is also the recommended way of implementing
2337 extra validation steps (e.g. link checkers) for every HTML page
2338 received. L</warn> and L</die> would then come in handy to signal
2339 validation errors.
2340  
2341 =cut
2342  
2343 sub update_html {
2344 29 ▶ my $self = shift;
Subroutine update_html: called CC=1 SCAR=0.0
Pod documented
2345 29 my $html = shift;
2346  
2347 29 $self->_reset_page;
2348 29 $self->{ct} = 'text/html';
2349 29 $self->{content} = $html;
2350  
2351 29 return;
2352 }
2353  
2354 =head2 $mech->credentials( $username, $password )
2355  
2356 Provide credentials to be used for HTTP Basic authentication for
2357 all sites and realms until further notice.
2358  
2359 The four argument form described in L<LWP::UserAgent> is still
2360 supported.
2361  
2362 =cut
2363  
2364 sub credentials {
2365 7 ▶ my $self = shift;
Subroutine credentials: called CC=5 SCAR=16.5
Pod documented
2366  
2367 # The lastest LWP::UserAgent also supports 2 arguments,
2368 # in which case the first is host:port
2369 7 ▶ if (@_ == 4 || (@_ == 2 && $_[0] =~ /:\d+$/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 4 or @_ == 2 and $_[0] =~ /:\d+$/) 4 3 7
Condition66%4/6
@_ == 4 or @_ == 2 and $_[0] =~ /:\d+$/
l!l&&r!l&&!r
043
@_ == 2 and $_[0] =~ /:\d+$/
!ll&&!rl&&r
034
MC/DC33%1/3
@_ == 4 or @_ == 2 and $_[0] =~ /:\d+$/
@_ == 4 @_ == 2 $_[0] =~ /:\d+$/
Truth table50%2/4
A or B and C
A= @_ == 4B= @_ == 2C= $_[0] =~ /:\d+$/
ABCresult
1XX1
0111
00X0
0100
2370 4 return $self->SUPER::credentials(@_);
2371 }
2372  
2373 3 ▶ @_ == 2
Branch: 1 branch
BranchTrueFalseTotal
@_ == 2 or $self->die("Invalid # of args for overridden credentials()") 0 3 3
2374 or $self->die( 'Invalid # of args for overridden credentials()' );
2375  
2376 3 return @$self{qw( __username __password )} = @_;
2377 }
2378  
2379 =head2 $mech->get_basic_credentials( $realm, $uri, $isproxy )
2380  
2381 Returns the credentials for the realm and URI.
2382  
2383 =cut
2384  
2385 sub get_basic_credentials {
2386 9 ▶ my $self = shift;
Subroutine get_basic_credentials: called CC=2 SCAR=6.9
Pod documented
2387 9 my @cred = grep { defined } @$self{qw( __username __password )};
2388 9 ▶ return @cred if @cred == 2;
Branch: 1 branch
BranchTrueFalseTotal
if @cred == 2 5 4 9
2389 4 return $self->SUPER::get_basic_credentials(@_);
2390 }
2391  
2392 =head2 $mech->clear_credentials()
2393  
2394 Remove any credentials set up with C<credentials()>.
2395  
2396 =cut
2397  
2398 sub clear_credentials {
2399 1 ▶ my $self = shift;
Subroutine clear_credentials: called CC=1 SCAR=0.0
Pod documented
2400 1 delete @$self{qw( __username __password )};
2401 }
2402  
2403 =head1 INHERITED UNCHANGED LWP::UserAgent METHODS
2404  
2405 As a sublass of L<LWP::UserAgent>, WWW::Mechanize inherits all of
2406 L<LWP::UserAgent>'s methods. Many of which are overridden or
2407 extended. The following methods are inherited unchanged. View the
2408 L<LWP::UserAgent> documentation for their implementation descriptions.
2409  
2410 This is not meant to be an inclusive list. LWP::UA may have added
2411 others.
2412  
2413 =head2 $mech->head()
2414  
2415 Inherited from L<LWP::UserAgent>.
2416  
2417 =head2 $mech->post()
2418  
2419 Inherited from L<LWP::UserAgent>.
2420  
2421 =head2 $mech->mirror()
2422  
2423 Inherited from L<LWP::UserAgent>.
2424  
2425 =head2 $mech->simple_request()
2426  
2427 Inherited from L<LWP::UserAgent>.
2428  
2429 =head2 $mech->is_protocol_supported()
2430  
2431 Inherited from L<LWP::UserAgent>.
2432  
2433 =head2 $mech->prepare_request()
2434  
2435 Inherited from L<LWP::UserAgent>.
2436  
2437 =head2 $mech->progress()
2438  
2439 Inherited from L<LWP::UserAgent>.
2440  
2441 =head1 INTERNAL-ONLY METHODS
2442  
2443 These methods are only used internally. You probably don't need to
2444 know about them.
2445  
2446 =head2 $mech->_update_page($request, $response)
2447  
2448 Updates all internal variables in $mech as if $request was just
2449 performed, and returns $response. The page stack is B<not> altered by
2450 this method, it is up to caller (e.g. L</request>) to do that.
2451  
2452 =cut
2453  
2454 sub _update_page {
2455 37 ▶ my ($self, $request, $res) = @_;
Subroutine _update_page: called CC=7 SCAR=19.5
2456  
2457 37 $self->{req} = $request;
2458 37 $self->{redirected_uri} = $request->uri->as_string;
2459  
2460 37 $self->{res} = $res;
2461  
2462 37 $self->{status} = $res->code;
2463 37 $self->{base} = $res->base;
2464 37 ▶ $self->{ct} = $res->content_type || '';
Condition100%2/2
$res->content_type || ''
l!l
325
MC/DC100%1/1
$res->content_type || ''
$res->content_type
Truth table100%2/2
A
A= $res->content_type
Aresult
11
00
2465  
2466 37 ▶ if ( $res->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_success) 34 3 37
2467 34 $self->{uri} = $self->{redirected_uri};
2468 34 $self->{last_uri} = $self->{uri};
2469 }
2470  
2471 37 ▶ if ( $res->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 3 34 37
2472 3 ▶ if ( $self->{autocheck} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"autocheck"}) 1 2 3
2473 1 $self->die( 'Error ', $request->method, 'ing ', $request->uri, ': ', $res->message );
2474 }
2475 }
2476  
2477 36 $self->_reset_page;
2478  
2479 # Try to decode the content. Undef will be returned if there's nothing to decompress.
2480 # See docs in HTTP::Message for details. Do we need to expose the options there?
2481 36 my $content = $res->decoded_content();
2482 36 ▶ $content = $res->content if (not defined $content);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 36 36
2483  
2484 36 $content .= _taintedness();
2485  
2486 36 ▶ if ($self->is_html) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_html) { } 28 8 36
2487 28 $self->update_html($content);
2488 }
2489 else {
2490 8 $self->{content} = $content;
2491 }
2492  
2493 36 return $res;
2494 } # _update_page
2495  
2496 47 our $_taintbrush;
2497  
2498 # This is lifted wholesale from Test::Taint
2499 sub _taintedness {
2500 36 ▶ return $_taintbrush if defined $_taintbrush;
Subroutine _taintedness: called CC=9 SCAR=22.2
Branch: 1 branch
BranchTrueFalseTotal
if defined $WWW::Mechanize::_taintbrush 14 22 36
2501  
2502 # Somehow we need to get some taintedness into our $_taintbrush.
2503 # Let's try the easy way first. Either of these should be
2504 # tainted, unless somebody has untainted them, so this
2505 # will almost always work on the first try.
2506 # (Unless, of course, taint checking has been turned off!)
2507 22 $_taintbrush = substr("$0$^X", 0, 0);
2508 22 ▶ return $_taintbrush if _is_tainted( $_taintbrush );
Branch: 1 branch
BranchTrueFalseTotal
if _is_tainted($WWW::Mechanize::_taintbrush) 18 4 22
2509  
2510 # Let's try again. Maybe somebody cleaned those.
2511 4 $_taintbrush = substr(join('', grep { defined } @ARGV, %ENV), 0, 0);
2512 4 ▶ return $_taintbrush if _is_tainted( $_taintbrush );
Branch: 1 branch
BranchTrueFalseTotal
if _is_tainted($WWW::Mechanize::_taintbrush) 0 4 4
2513  
2514 # If those don't work, go try to open some file from some unsafe
2515 # source and get data from them. That data is tainted.
2516 # (Yes, even reading from /dev/null works!)
2517 4 for my $filename ( qw(/dev/null / . ..), values %INC, $0, $^X ) {
2518 844 ▶ if ( open my $fh, '<', $filename ) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<", $filename) 844 0 844
2519 844 my $data;
2520 844 ▶ if ( defined sysread $fh, $data, 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined sysread($fh, $data, 1)) 832 12 844
2521 832 $_taintbrush = substr( $data, 0, 0 );
2522 832 ▶ last if _is_tainted( $_taintbrush );
Branch: 1 branch
BranchTrueFalseTotal
if _is_tainted($WWW::Mechanize::_taintbrush) 0 832 832
2523 }
2524 }
2525 }
2526  
2527 # Sanity check
2528 4 ▶ die "Our taintbrush should have zero length!" if length $_taintbrush;
Branch: 1 branch
BranchTrueFalseTotal
if length $WWW::Mechanize::_taintbrush 0 4 4
2529  
2530 4 return $_taintbrush;
2531 }
2532  
2533 sub _is_tainted {
2534 47 ▶ no warnings qw(void uninitialized);
Subroutine BEGIN: called CC=1 SCAR=0.0
2535  
2536 858 ▶ return !eval { join('', shift), kill 0; 1 };
Subroutine _is_tainted: called CC=1 SCAR=0.0
2537 } # _is_tainted
2538  
2539  
2540 =head2 $mech->_modify_request( $req )
2541  
2542 Modifies a L<HTTP::Request> before the request is sent out,
2543 for both GET and POST requests.
2544  
2545 We add a C<Referer> header, as well as header to note that we can accept gzip
2546 encoded content, if L<Compress::Zlib> is installed.
2547  
2548 =cut
2549  
2550 sub _modify_request {
2551 38 ▶ my $self = shift;
Subroutine _modify_request: called CC=7 SCAR=19.5
2552 38 my $req = shift;
2553  
2554 # add correct Accept-Encoding header to restore compliance with
2555 # http://www.freesoft.org/CIE/RFC/2068/158.htm
2556 # http://use.perl.org/~rhesa/journal/25952
2557 38 ▶ if (not $req->header( 'Accept-Encoding' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($req->header("Accept-Encoding")) 37 1 38
2558 # "identity" means "please! unencoded content only!"
2559 37 ▶ $req->header( 'Accept-Encoding', $HAS_ZLIB ? 'gzip' : 'identity' );
Branch: 1 branch
BranchTrueFalseTotal
$WWW::Mechanize::HAS_ZLIB ? : 37 0 37
2560 }
2561  
2562 38 my $last = $self->{last_uri};
2563 38 ▶ if ( $last ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last) 13 25 38
2564 13 ▶ $last = $last->as_string if ref($last);
Branch: 1 branch
BranchTrueFalseTotal
if ref $last 0 13 13
2565 13 $req->header( Referer => $last );
2566 }
2567 38 ▶ while ( my($key,$value) = each %{$self->{headers}} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$self{"headers"};}) 4 38 42
2568 4 ▶ if ( defined $value ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 3 1 4
2569 3 $req->header( $key => $value );
2570 }
2571 else {
2572 1 $req->remove_header( $key );
2573 }
2574 }
2575  
2576 38 return $req;
2577 }
2578  
2579  
2580 =head2 $mech->_make_request()
2581  
2582 Convenience method to make it easier for subclasses like
2583 L<WWW::Mechanize::Cached> to intercept the request.
2584  
2585 =cut
2586  
2587 sub _make_request {
2588 36 ▶ my $self = shift;
Subroutine _make_request: called CC=1 SCAR=0.0
2589 36 return $self->SUPER::request(@_);
2590 }
2591  
2592 =head2 $mech->_reset_page()
2593  
2594 Resets the internal fields that track page parsed stuff.
2595  
2596 =cut
2597  
2598 sub _reset_page {
2599 110 ▶ my $self = shift;
Subroutine _reset_page: called CC=1 SCAR=0.0
2600  
2601 110 $self->{links} = undef;
2602 110 $self->{images} = undef;
2603 110 $self->{forms} = undef;
2604 110 $self->{current_form} = undef;
2605 110 $self->{title} = undef;
2606 110 $self->{text} = undef;
2607  
2608 110 return;
2609 }
2610  
2611 =head2 $mech->_extract_links()
2612  
2613 Extracts links from the content of a webpage, and populates the C<{links}>
2614 property with L<WWW::Mechanize::Link> objects.
2615  
2616 =cut
2617  
2618 47 my %link_tags = (
2619 a => 'href',
2620 area => 'href',
2621 frame => 'src',
2622 iframe => 'src',
2623 link => 'href',
2624 meta => 'content',
2625 );
2626  
2627 sub _extract_links {
2628 7 ▶ my $self = shift;
Subroutine _extract_links: called CC=4 SCAR=13.9
2629  
2630  
2631 7 $self->{links} = [];
2632 7 ▶ if ( defined $self->{content} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"content"}) 6 1 7
2633 6 my $parser = HTML::TokeParser->new(\$self->{content});
2634 6 ▶ while ( my $token = $parser->get_tag( keys %link_tags ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $token = $parser->get_tag(keys %link_tags)) 68 6 74
2635 68 my $link = $self->_link_from_token( $token, $parser );
2636 68 ▶ push( @{$self->{links}}, $link ) if $link;
Branch: 1 branch
BranchTrueFalseTotal
if $link 62 6 68
2637 } # while
2638 }
2639  
2640 7 return;
2641 }
2642  
2643  
2644 47 my %image_tags = (
2645 img => 'src',
2646 input => 'src',
2647 );
2648  
2649 sub _extract_images {
2650 2 ▶ my $self = shift;
Subroutine _extract_images: called CC=4 SCAR=13.9
2651  
2652 2 $self->{images} = [];
2653  
2654 2 ▶ if ( defined $self->{content} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"content"}) 2 0 2
2655 2 my $parser = HTML::TokeParser->new(\$self->{content});
2656 2 ▶ while ( my $token = $parser->get_tag( keys %image_tags ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $token = $parser->get_tag(keys %image_tags)) 8 2 10
2657 8 my $image = $self->_image_from_token( $token, $parser );
2658 8 ▶ push( @{$self->{images}}, $image ) if $image;
Branch: 1 branch
BranchTrueFalseTotal
if $image 6 2 8
2659 } # while
2660 }
2661  
2662 2 return;
2663 }
2664  
2665 sub _image_from_token {
2666 8 ▶ my $self = shift;
Subroutine _image_from_token: called CC=4 SCAR=13.9
2667 8 my $token = shift;
2668 8 my $parser = shift;
2669  
2670 8 my $tag = $token->[0];
2671 8 my $attrs = $token->[1];
2672  
2673 8 ▶ if ( $tag eq 'input' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag eq "input") 4 4 8
2674 4 ▶ my $type = $attrs->{type} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $type = $attrs->{"type"} or return 0 4 4
2675 4 ▶ return unless $type eq 'image';
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "image" 2 2 4
2676 }
2677  
2678 6 require WWW::Mechanize::Image;
2679 return
2680 WWW::Mechanize::Image->new({
2681 tag => $tag,
2682 base => $self->base,
2683 url => $attrs->{src},
2684 name => $attrs->{name},
2685 height => $attrs->{height},
2686 width => $attrs->{width},
2687 alt => $attrs->{alt},
2688 6 });
2689 }
2690  
2691 sub _link_from_token {
2692 68 ▶ my $self = shift;
Subroutine _link_from_token: called CC=12 SCAR=25.1
2693 68 my $token = shift;
2694 68 my $parser = shift;
2695  
2696 68 my $tag = $token->[0];
2697 68 my $attrs = $token->[1];
2698 68 my $url = $attrs->{$link_tags{$tag}};
2699  
2700 68 my $text;
2701 my $name;
2702 68 ▶ if ( $tag eq 'a' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag eq "a") 33 35 68
2703 33 $text = $parser->get_trimmed_text("/$tag");
2704 33 ▶ $text = '' unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 33 33
2705  
2706 33 my $onClick = $attrs->{onclick};
2707 33 ▶ if ( $onClick && ($onClick =~ /^window\.open\(\s*'([^']+)'/) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($onClick and $onClick =~ /^window\.open\(\s*'([^']+)'/) 2 31 33
Condition66%2/3
$onClick and $onClick =~ /^window\.open\(\s*'([^']+)'/
!ll&&!rl&&r
3102
MC/DC50%1/2
$onClick and $onClick =~ /^window\.open\(\s*'([^']+)'/
$onClick $onClick =~ /^window\.open\(\s*'([^']+)'/
Truth table66%2/3
A and B
A= $onClickB= $onClick =~ /^window\.open\(\s*'([^']+)'/
ABresult
0X0
100
111
2708 2 $url = $1;
2709 }
2710 } # a
2711  
2712 # Of the tags we extract from, only 'AREA' has an alt tag
2713 # The rest should have a 'name' attribute.
2714 # ... but we don't do anything with that bit of wisdom now.
2715  
2716 68 $name = $attrs->{name};
2717  
2718 68 ▶ if ( $tag eq 'meta' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag eq "meta") 9 59 68
2719 9 my $equiv = $attrs->{'http-equiv'};
2720 9 my $content = $attrs->{'content'};
2721 9 ▶ return unless $equiv && (lc $equiv eq 'refresh') && defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $equiv and lc $equiv eq "refresh" and defined $content 3 4 7
Condition83%5/6
$equiv and lc $equiv eq "refresh" and defined $content
!ll&&!rl&&r
504
$equiv and lc $equiv eq "refresh"
!ll&&!rl&&r
234
MC/DC66%2/3
$equiv and lc $equiv eq "refresh" and defined $content
$equiv lc $equiv eq "refresh" defined $content
Truth table75%3/4
A and B and C
A= $equivB= lc $equiv eq "refresh"C= defined $content
ABCresult
0XX0
10X0
1100
1111
2722  
2723 4 ▶ if ( $content =~ /^\d+\s*;\s*url\s*=\s*(\S+)/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content =~ /^\d+\s*;\s*url\s*=\s*(\S+)/i) { } 4 0 4
2724 4 $url = $1;
2725 4 ▶ $url =~ s/^"(.+)"$/$1/ or $url =~ s/^'(.+)'$/$1/;
Branch: 1 branch
BranchTrueFalseTotal
$url =~ s/^"(.+)"$/$1/ or $url =~ s/^'(.+)'$/$1/ 4 0 4
2726 }
2727 else {
2728 0 undef $url;
2729 }
2730 } # meta
2731  
2732 63 ▶ return unless defined $url; # probably just a name link or <AREA NOHREF...>
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url 1 62 63
2733  
2734 62 require WWW::Mechanize::Link;
2735 return
2736 62 WWW::Mechanize::Link->new({
2737 url => $url,
2738 text => $text,
2739 name => $name,
2740 tag => $tag,
2741 base => $self->base,
2742 attrs => $attrs,
2743 });
2744 } # _link_from_token
2745  
2746  
2747 sub _extract_forms {
2748 8 ▶ my $self = shift;
Subroutine _extract_forms: called CC=4 SCAR=13.9
2749  
2750 8 my @forms = HTML::Form->parse( $self->content, $self->base );
2751 8 $self->{forms} = \@forms;
2752 8 for my $form ( @forms ) {
2753 12 for my $input ($form->inputs) {
2754 46 ▶ if ($input->type eq 'file') {
Branch: 1 branch
BranchTrueFalseTotal
if ($input->type eq "file") 1 45 46
2755 1 $input->value( undef );
2756 }
2757 }
2758 }
2759  
2760 8 return;
2761 }
2762  
2763 =head2 $mech->_push_page_stack()
2764  
2765 The agent keeps a stack of visited pages, which it can pop when it needs
2766 to go BACK and so on.
2767  
2768 The current page needs to be pushed onto the stack before we get a new
2769 page, and the stack needs to be popped when BACK occurs.
2770  
2771 Neither of these take any arguments, they just operate on the $mech
2772 object.
2773  
2774 =cut
2775  
2776 sub _push_page_stack {
2777 36 ▶ my $self = shift;
Subroutine _push_page_stack: called CC=6 SCAR=19.3
2778  
2779 36 my $req = $self->{req};
2780 36 my $res = $self->{res};
2781  
2782 36 ▶ return unless $req && $res && $self->stack_depth;
Branch: 1 branch
BranchTrueFalseTotal
unless $req and $res and $self->stack_depth 0 13 13
Condition66%4/6
$req and $res and $self->stack_depth
!ll&&!rl&&r
23013
$req and $res
!ll&&!rl&&r
23013
MC/DC33%1/3
$req and $res and $self->stack_depth
$req $res $self->stack_depth
Truth table50%2/4
A and B and C
A= $reqB= $resC= $self->stack_depth
ABCresult
0XX0
10X0
1100
1111
2783  
2784 # Don't push anything if it's a virgin object
2785 13 ▶ my $stack = $self->{page_stack} ||= [];
Condition50%1/2
$self->{"page_stack"} ||= []
l!l
130
MC/DC0%0/1
$self->{"page_stack"} ||= []
$self->{"page_stack"}
Truth table50%1/2
A
A= $self->{"page_stack"}
Aresult
11
00
2786 13 ▶ if ( @{$stack} >= $self->stack_depth ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stack;} >= $self->stack_depth) 0 13 13
2787 0 shift @{$stack};
2788 }
2789 13 push( @{$stack}, { req => $req, res => $res } );
2790  
2791 13 return 1;
2792 }
2793  
2794 =head2 warn( @messages )
2795  
2796 Centralized warning method, for diagnostics and non-fatal problems.
2797 Defaults to calling C<CORE::warn>, but may be overridden by setting
2798 C<onwarn> in the constructor.
2799  
2800 =cut
2801  
2802 sub warn {
2803 24 ▶ my $self = shift;
Subroutine warn: called CC=3 SCAR=11.0
Pod documented
2804  
2805 24 ▶ return unless my $handler = $self->{onwarn};
Branch: 1 branch
BranchTrueFalseTotal
unless my $handler = $self->{"onwarn"} 0 24 24
2806  
2807 24 ▶ return if $self->quiet;
Branch: 1 branch
BranchTrueFalseTotal
if $self->quiet 2 22 24
2808  
2809 22 return $handler->(@_);
2810 }
2811  
2812 =head2 die( @messages )
2813  
2814 Centralized error method. Defaults to calling C<CORE::die>, but
2815 may be overridden by setting C<onerror> in the constructor.
2816  
2817 =cut
2818  
2819 sub die {
2820 3 ▶ my $self = shift;
Subroutine die: called CC=2 SCAR=6.9
Pod documented
2821  
2822 3 ▶ return unless my $handler = $self->{onerror};
Branch: 1 branch
BranchTrueFalseTotal
unless my $handler = $self->{"onerror"} 1 2 3
2823  
2824 2 return $handler->(@_);
2825 }
2826  
2827  
2828 # NOT an object method!
2829 sub _warn {
2830 22 ▶ require Carp;
Subroutine _warn: called CC=1 SCAR=0.0
2831 22 return &Carp::carp; ## no critic
2832 }
2833  
2834 # NOT an object method!
2835 sub _die {
2836 2 ▶ require Carp;
Subroutine _die: called CC=1 SCAR=0.0
2837 2 return &Carp::croak; ## no critic
2838 }
2839  
2840 47 1; # End of module
2841  
2842 __END__
↑ Summary lib/WWW/Mechanize/Image.pm »