Code Monkey home page Code Monkey logo

www-mechanize's Introduction

NAME

LWP::UserAgent - Web user agent class

SYNOPSIS

use strict;
use warnings;

use LWP::UserAgent ();

my $ua = LWP::UserAgent->new(timeout => 10);
$ua->env_proxy;

my $response = $ua->get('http://example.com');

if ($response->is_success) {
    print $response->decoded_content;
}
else {
    die $response->status_line;
}

Extra layers of security (note the cookie_jar and protocols_allowed):

use strict;
use warnings;

use HTTP::CookieJar::LWP ();
use LWP::UserAgent       ();

my $jar = HTTP::CookieJar::LWP->new;
my $ua  = LWP::UserAgent->new(
    cookie_jar        => $jar,
    protocols_allowed => ['http', 'https'],
    timeout           => 10,
);

$ua->env_proxy;

my $response = $ua->get('http://example.com');

if ($response->is_success) {
    print $response->decoded_content;
}
else {
    die $response->status_line;
}

DESCRIPTION

The LWP::UserAgent is a class implementing a web user agent. LWP::UserAgent objects can be used to dispatch web requests.

In normal use the application creates an LWP::UserAgent object, and then configures it with values for timeouts, proxies, name, etc. It then creates an instance of HTTP::Request for the request that needs to be performed. This request is then passed to one of the request method the UserAgent, which dispatches it using the relevant protocol, and returns a HTTP::Response object. There are convenience methods for sending the most common request types: "get" in LWP::UserAgent, "head" in LWP::UserAgent, "post" in LWP::UserAgent, "put" in LWP::UserAgent and "delete" in LWP::UserAgent. When using these methods, the creation of the request object is hidden as shown in the synopsis above.

The basic approach of the library is to use HTTP-style communication for all protocol schemes. This means that you will construct HTTP::Request objects and receive HTTP::Response objects even for non-HTTP resources like gopher and ftp. In order to achieve even more similarity to HTTP-style communications, gopher menus and file directories are converted to HTML documents.

CONSTRUCTOR METHODS

The following constructor methods are available:

clone

my $ua2 = $ua->clone;

Returns a copy of the LWP::UserAgent object.

CAVEAT: Please be aware that the clone method does not copy or clone your cookie_jar attribute. Due to the limited restrictions on what can be used for your cookie jar, there is no way to clone the attribute. The cookie_jar attribute will be undef in the new object instance.

new

my $ua = LWP::UserAgent->new( %options )

This method constructs a new LWP::UserAgent object and returns it. Key/value pair arguments may be provided to set up the initial state. The following options correspond to attribute methods described below:

KEY                     DEFAULT
-----------             --------------------
agent                   "libwww-perl/#.###"
conn_cache              undef
cookie_jar              undef
cookie_jar_class        HTTP::Cookies
default_headers         HTTP::Headers->new
from                    undef
local_address           undef
max_redirect            7
max_size                undef
no_proxy                []
parse_head              1
protocols_allowed       undef
protocols_forbidden     undef
proxy                   {}
requests_redirectable   ['GET', 'HEAD']
send_te                 1
show_progress           undef
ssl_opts                { verify_hostname => 1 }
timeout                 180

The following additional options are also accepted: If the env_proxy option is passed in with a true value, then proxy settings are read from environment variables (see "env_proxy" in LWP::UserAgent). If env_proxy isn't provided, the PERL_LWP_ENV_PROXY environment variable controls if "env_proxy" in LWP::UserAgent is called during initialization. If the keep_alive option value is defined and non-zero, then an LWP::ConnCache is set up (see "conn_cache" in LWP::UserAgent). The keep_alive value is passed on as the total_capacity for the connection cache.

proxy must be set as an arrayref of key/value pairs. no_proxy takes an arrayref of domains.

ATTRIBUTES

The settings of the configuration attributes modify the behaviour of the LWP::UserAgent when it dispatches requests. Most of these can also be initialized by options passed to the constructor method.

The following attribute methods are provided. The attribute value is left unchanged if no argument is given. The return value from each method is the old attribute value.

agent

my $agent = $ua->agent;
$ua->agent('Checkbot/0.4 ');    # append the default to the end
$ua->agent('Mozilla/5.0');
$ua->agent("");                 # don't identify

Get/set the product token that is used to identify the user agent on the network. The agent value is sent as the User-Agent header in the requests.

The default is a string of the form libwww-perl/#.###, where #.### is substituted with the version number of this library.

If the provided string ends with space, the default libwww-perl/#.### string is appended to it.

The user agent string should be one or more simple product identifiers with an optional version number separated by the / character.

conn_cache

my $cache_obj = $ua->conn_cache;
$ua->conn_cache( $cache_obj );

Get/set the LWP::ConnCache object to use. See LWP::ConnCache for details.

cookie_jar

my $jar = $ua->cookie_jar;
$ua->cookie_jar( $cookie_jar_obj );

Get/set the cookie jar object to use. The only requirement is that the cookie jar object must implement the extract_cookies($response) and add_cookie_header($request) methods. These methods will then be invoked by the user agent as requests are sent and responses are received. Normally this will be a HTTP::Cookies object or some subclass. You are, however, encouraged to use HTTP::CookieJar::LWP instead. See "BEST PRACTICES" for more information.

use HTTP::CookieJar::LWP ();

my $jar = HTTP::CookieJar::LWP->new;
my $ua = LWP::UserAgent->new( cookie_jar => $jar );

# or after object creation
$ua->cookie_jar( $cookie_jar );

The default is to have no cookie jar, i.e. never automatically add Cookie headers to the requests.

If $jar contains an unblessed hash reference, a new cookie jar object is created for you automatically. The object is of the class set with the cookie_jar_class constructor argument, which defaults to HTTP::Cookies.

$ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });

is really just a shortcut for:

require HTTP::Cookies;
$ua->cookie_jar(HTTP::Cookies->new(file => "$ENV{HOME}/.cookies.txt"));

As described above and in "BEST PRACTICES", you should set cookie_jar_class to "HTTP::CookieJar::LWP" to get a safer cookie jar.

my $ua = LWP::UserAgent->new( cookie_jar_class => 'HTTP::CookieJar::LWP' );
$ua->cookie_jar({}); # HTTP::CookieJar::LWP takes no args

These can also be combined into the constructor, so a jar is created at instantiation.

my $ua = LWP::UserAgent->new(
  cookie_jar_class => 'HTTP::CookieJar::LWP',
  cookie_jar       =>  {},
);

credentials

my $creds = $ua->credentials();
$ua->credentials( $netloc, $realm );
$ua->credentials( $netloc, $realm, $uname, $pass );
$ua->credentials("www.example.com:80", "Some Realm", "foo", "secret");

Get/set the user name and password to be used for a realm.

The $netloc is a string of the form <host>:<port>. The username and password will only be passed to this server.

default_header

$ua->default_header( $field );
$ua->default_header( $field => $value );
$ua->default_header('Accept-Encoding' => scalar HTTP::Message::decodable());
$ua->default_header('Accept-Language' => "no, en");

This is just a shortcut for $ua->default_headers->header( $field => $value ).

default_headers

my $headers = $ua->default_headers;
$ua->default_headers( $headers_obj );

Get/set the headers object that will provide default header values for any requests sent. By default this will be an empty HTTP::Headers object.

from

my $from = $ua->from;
$ua->from('[email protected]');

Get/set the email address for the human user who controls the requesting user agent. The address should be machine-usable, as defined in RFC2822. The from value is sent as the From header in the requests.

The default is to not send a From header. See "default_headers" in LWP::UserAgent for the more general interface that allow any header to be defaulted.

local_address

my $address = $ua->local_address;
$ua->local_address( $address );

Get/set the local interface to bind to for network connections. The interface can be specified as a hostname or an IP address. This value is passed as the LocalAddr argument to IO::Socket::INET.

max_redirect

my $max = $ua->max_redirect;
$ua->max_redirect( $n );

This reads or sets the object's limit of how many times it will obey redirection responses in a given request cycle.

By default, the value is 7. This means that if you call "request" in LWP::UserAgent and the response is a redirect elsewhere which is in turn a redirect, and so on seven times, then LWP gives up after that seventh request.

max_size

my $size = $ua->max_size;
$ua->max_size( $bytes );

Get/set the size limit for response content. The default is undef, which means that there is no limit. If the returned response content is only partial, because the size limit was exceeded, then a Client-Aborted header will be added to the response. The content might end up longer than max_size as we abort once appending a chunk of data makes the length exceed the limit. The Content-Length header, if present, will indicate the length of the full content and will normally not be the same as length($res->content).

parse_head

my $bool = $ua->parse_head;
$ua->parse_head( $boolean );

Get/set a value indicating whether we should initialize response headers from the <head> section of HTML documents. The default is true. Do not turn this off unless you know what you are doing.

protocols_allowed

my $aref = $ua->protocols_allowed;      # get allowed protocols
$ua->protocols_allowed( \@protocols );  # allow ONLY these
$ua->protocols_allowed(undef);          # delete the list
$ua->protocols_allowed(['http',]);      # ONLY allow http

By default, an object has neither a protocols_allowed list, nor a "protocols_forbidden" in LWP::UserAgent list.

This reads (or sets) this user agent's list of protocols that the request methods will exclusively allow. The protocol names are case insensitive.

For example: $ua->protocols_allowed( [ 'http', 'https'] ); means that this user agent will allow only those protocols, and attempts to use this user agent to access URLs with any other schemes (like ftp://...) will result in a 500 error.

Note that having a protocols_allowed list causes any "protocols_forbidden" in LWP::UserAgent list to be ignored.

protocols_forbidden

my $aref = $ua->protocols_forbidden;    # get the forbidden list
$ua->protocols_forbidden(\@protocols);  # do not allow these
$ua->protocols_forbidden(['http',]);    # All http reqs get a 500
$ua->protocols_forbidden(undef);        # delete the list

This reads (or sets) this user agent's list of protocols that the request method will not allow. The protocol names are case insensitive.

For example: $ua->protocols_forbidden( [ 'file', 'mailto'] ); means that this user agent will not allow those protocols, and attempts to use this user agent to access URLs with those schemes will result in a 500 error.

requests_redirectable

my $aref = $ua->requests_redirectable;
$ua->requests_redirectable( \@requests );
$ua->requests_redirectable(['GET', 'HEAD',]); # the default

This reads or sets the object's list of request names that "redirect_ok" in LWP::UserAgent will allow redirection for. By default, this is ['GET', 'HEAD'], as per RFC 2616. To change to include POST, consider:

push @{ $ua->requests_redirectable }, 'POST';

send_te

my $bool = $ua->send_te;
$ua->send_te( $boolean );

If true, will send a TE header along with the request. The default is true. Set it to false to disable the TE header for systems who can't handle it.

show_progress

my $bool = $ua->show_progress;
$ua->show_progress( $boolean );

Get/set a value indicating whether a progress bar should be displayed on the terminal as requests are processed. The default is false.

ssl_opts

my @keys = $ua->ssl_opts;
my $val = $ua->ssl_opts( $key );
$ua->ssl_opts( $key => $value );

Get/set the options for SSL connections. Without argument return the list of options keys currently set. With a single argument return the current value for the given option. With 2 arguments set the option value and return the old. Setting an option to the value undef removes this option.

The options that LWP relates to are:

  • verify_hostname => $bool

    When TRUE LWP will for secure protocol schemes ensure it connects to servers that have a valid certificate matching the expected hostname. If FALSE no checks are made and you can't be sure that you communicate with the expected peer. The no checks behaviour was the default for libwww-perl-5.837 and earlier releases.

    This option is initialized from the PERL_LWP_SSL_VERIFY_HOSTNAME environment variable. If this environment variable isn't set; then verify_hostname defaults to 1.

    Please note that that recently the overall effect of this option with regards to SSL handling has changed. As of version 6.11 of LWP::Protocol::https, which is an external module, SSL certificate verification was harmonized to behave in sync with IO::Socket::SSL. With this change, setting this option no longer disables all SSL certificate verification, only the hostname checks. To disable all verification, use the SSL_verify_mode option in the ssl_opts attribute. For example: $ua-ssl_opts(SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE);>

  • SSL_ca_file => $path

    The path to a file containing Certificate Authority certificates. A default setting for this option is provided by checking the environment variables PERL_LWP_SSL_CA_FILE and HTTPS_CA_FILE in order.

  • SSL_ca_path => $path

    The path to a directory containing files containing Certificate Authority certificates. A default setting for this option is provided by checking the environment variables PERL_LWP_SSL_CA_PATH and HTTPS_CA_DIR in order.

Other options can be set and are processed directly by the SSL Socket implementation in use. See IO::Socket::SSL or Net::SSL for details.

The libwww-perl core no longer bundles protocol plugins for SSL. You will need to install LWP::Protocol::https separately to enable support for processing https-URLs.

timeout

my $secs = $ua->timeout;
$ua->timeout( $secs );

Get/set the timeout value in seconds. The default value is 180 seconds, i.e. 3 minutes.

The request is aborted if no activity on the connection to the server is observed for timeout seconds. This means that the time it takes for the complete transaction and the "request" in LWP::UserAgent method to actually return might be longer.

When a request times out, a response object is still returned. The response will have a standard HTTP Status Code (500). This response will have the "Client-Warning" header set to the value of "Internal response". See the "get" in LWP::UserAgent method description below for further details.

PROXY ATTRIBUTES

The following methods set up when requests should be passed via a proxy server.

env_proxy

$ua->env_proxy;

Load proxy settings from *_proxy environment variables. You might specify proxies like this (sh-syntax):

gopher_proxy=http://proxy.my.place/
wais_proxy=http://proxy.my.place/
no_proxy="localhost,example.com"
export gopher_proxy wais_proxy no_proxy

csh or tcsh users should use the setenv command to define these environment variables.

On systems with case insensitive environment variables there exists a name clash between the CGI environment variables and the HTTP_PROXY environment variable normally picked up by env_proxy. Because of this HTTP_PROXY is not honored for CGI scripts. The CGI_HTTP_PROXY environment variable can be used instead.

no_proxy

$ua->no_proxy( @domains );
$ua->no_proxy('localhost', 'example.com');
$ua->no_proxy(); # clear the list

Do not proxy requests to the given domains, including subdomains. Calling no_proxy without any domains clears the list of domains.

proxy

$ua->proxy(\@schemes, $proxy_url)
$ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/');

# For a single scheme:
$ua->proxy($scheme, $proxy_url)
$ua->proxy('gopher', 'http://proxy.sn.no:8001/');

# To set multiple proxies at once:
$ua->proxy([
    ftp => 'http://ftp.example.com:8001/',
    [ 'http', 'https' ] => 'http://http.example.com:8001/',
]);

Set/retrieve proxy URL for a scheme.

The first form specifies that the URL is to be used as a proxy for access methods listed in the list in the first method argument, i.e. http and ftp.

The second form shows a shorthand form for specifying proxy URL for a single access scheme.

The third form demonstrates setting multiple proxies at once. This is also the only form accepted by the constructor.

HANDLERS

Handlers are code that injected at various phases during the processing of requests. The following methods are provided to manage the active handlers:

add_handler

$ua->add_handler( $phase => \&cb, %matchspec )

Add handler to be invoked in the given processing phase. For how to specify %matchspec see "Matching" in HTTP::Config.

The possible values $phase and the corresponding callback signatures are as follows. Note that the handlers are documented in the order in which they will be run, which is:

request_preprepare
request_prepare
request_send
response_header
response_data
response_done
response_redirect
  • request_preprepare => sub { my($request, $ua, $handler) = @_; ... }

    The handler is called before the request_prepare and other standard initialization of the request. This can be used to set up headers and attributes that the request_prepare handler depends on. Proxy initialization should take place here; but in general don't register handlers for this phase.

  • request_prepare => sub { my($request, $ua, $handler) = @_; ... }

    The handler is called before the request is sent and can modify the request any way it see fit. This can for instance be used to add certain headers to specific requests.

    The method can assign a new request object to $_[0] to replace the request that is sent fully.

    The return value from the callback is ignored. If an exception is raised it will abort the request and make the request method return a "400 Bad request" response.

  • request_send => sub { my($request, $ua, $handler) = @_; ... }

    This handler gets a chance of handling requests before they're sent to the protocol handlers. It should return an HTTP::Response object if it wishes to terminate the processing; otherwise it should return nothing.

    The response_header and response_data handlers will not be invoked for this response, but the response_done will be.

  • response_header => sub { my($response, $ua, $handler) = @_; ... }

    This handler is called right after the response headers have been received, but before any content data. The handler might set up handlers for data and might croak to abort the request.

    The handler might set the $response->{default_add_content} value to control if any received data should be added to the response object directly. This will initially be false if the $ua->request() method was called with a $content_file or $content_cb argument; otherwise true.

  • response_data => sub { my($response, $ua, $handler, $data) = @_; ... }

    This handler is called for each chunk of data received for the response. The handler might croak to abort the request.

    This handler needs to return a TRUE value to be called again for subsequent chunks for the same request.

  • response_done => sub { my($response, $ua, $handler) = @_; ... }

    The handler is called after the response has been fully received, but before any redirect handling is attempted. The handler can be used to extract information or modify the response.

  • response_redirect => sub { my($response, $ua, $handler) = @_; ... }

    The handler is called in $ua->request after response_done. If the handler returns an HTTP::Request object we'll start over with processing this request instead.

For all of these, $handler is a code reference to the handler that is currently being run.

get_my_handler

$ua->get_my_handler( $phase, %matchspec );
$ua->get_my_handler( $phase, %matchspec, $init );

Will retrieve the matching handler as hash ref.

If $init is passed as a true value, create and add the handler if it's not found. If $init is a subroutine reference, then it's called with the created handler hash as argument. This sub might populate the hash with extra fields; especially the callback. If $init is a hash reference, merge the hashes.

handlers

$ua->handlers( $phase, $request )
$ua->handlers( $phase, $response )

Returns the handlers that apply to the given request or response at the given processing phase.

remove_handler

$ua->remove_handler( undef, %matchspec );
$ua->remove_handler( $phase, %matchspec );
$ua->remove_handler(); # REMOVE ALL HANDLERS IN ALL PHASES

Remove handlers that match the given %matchspec. If $phase is not provided, remove handlers from all phases.

Be careful as calling this function with %matchspec that is not specific enough can remove handlers not owned by you. It's probably better to use the "set_my_handler" in LWP::UserAgent method instead.

The removed handlers are returned.

set_my_handler

$ua->set_my_handler( $phase, $cb, %matchspec );
$ua->set_my_handler($phase, undef); # remove handler for phase

Set handlers private to the executing subroutine. Works by defaulting an owner field to the %matchspec that holds the name of the called subroutine. You might pass an explicit owner to override this.

If $cb is passed as undef, remove the handler.

REQUEST METHODS

The methods described in this section are used to dispatch requests via the user agent. The following request methods are provided:

delete

my $res = $ua->delete( $url );
my $res = $ua->delete( $url, $field_name => $value, ... );

This method will dispatch a DELETE request on the given URL. Additional headers and content options are the same as for the "get" in LWP::UserAgent method.

This method will use the DELETE() function from HTTP::Request::Common to build the request. See HTTP::Request::Common for a details on how to pass form content and other advanced features.

get

my $res = $ua->get( $url );
my $res = $ua->get( $url , $field_name => $value, ... );

This method will dispatch a GET request on the given URL. Further arguments can be given to initialize the headers of the request. These are given as separate name/value pairs. The return value is a response object. See HTTP::Response for a description of the interface it provides.

There will still be a response object returned when LWP can't connect to the server specified in the URL or when other failures in protocol handlers occur. These internal responses use the standard HTTP status codes, so the responses can't be differentiated by testing the response status code alone. Error responses that LWP generates internally will have the "Client-Warning" header set to the value "Internal response". If you need to differentiate these internal responses from responses that a remote server actually generates, you need to test this header value.

Fields names that start with ":" are special. These will not initialize headers of the request but will determine how the response content is treated. The following special field names are recognized:

':content_file'   => $filename # or $filehandle
':content_cb'     => \&callback
':read_size_hint' => $bytes

If a $filename or $filehandle is provided with the :content_file option, then the response content will be saved here instead of in the response object. The $filehandle may also be an object with an open file descriptor, such as a File::Temp object. If a callback is provided with the :content_cb option then this function will be called for each chunk of the response content as it is received from the server. If neither of these options are given, then the response content will accumulate in the response object itself. This might not be suitable for very large response bodies. Only one of :content_file or :content_cb can be specified. The content of unsuccessful responses will always accumulate in the response object itself, regardless of the :content_file or :content_cb options passed in. Note that errors writing to the content file (for example due to permission denied or the filesystem being full) will be reported via the Client-Aborted or X-Died response headers, and not the is_success method.

The :read_size_hint option is passed to the protocol module which will try to read data from the server in chunks of this size. A smaller value for the :read_size_hint will result in a higher number of callback invocations.

The callback function is called with 3 arguments: a chunk of data, a reference to the response object, and a reference to the protocol object. The callback can abort the request by invoking die(). The exception message will show up as the "X-Died" header field in the response returned by the $ua->get() method.

head

my $res = $ua->head( $url );
my $res = $ua->head( $url , $field_name => $value, ... );

This method will dispatch a HEAD request on the given URL. Otherwise it works like the "get" in LWP::UserAgent method described above.

is_protocol_supported

my $bool = $ua->is_protocol_supported( $scheme );

You can use this method to test whether this user agent object supports the specified scheme. (The scheme might be a string (like http or ftp) or it might be an URI object reference.)

Whether a scheme is supported is determined by the user agent's protocols_allowed or protocols_forbidden lists (if any), and by the capabilities of LWP. I.e., this will return true only if LWP supports this protocol and it's permitted for this particular object.

is_online

my $bool = $ua->is_online;

Tries to determine if you have access to the Internet. Returns 1 (true) if the built-in heuristics determine that the user agent is able to access the Internet (over HTTP) or 0 (false).

See also LWP::Online.

mirror

my $res = $ua->mirror( $url, $filename );

This method will get the document identified by URL and store it in file called $filename. If the file already exists, then the request will contain an If-Modified-Since header matching the modification time of the file. If the document on the server has not changed since this time, then nothing happens. If the document has been updated, it will be downloaded again. The modification time of the file will be forced to match that of the server.

Uses "move" in File::Copy to attempt to atomically replace the $filename.

The return value is an HTTP::Response object.

patch

# Any version of HTTP::Message works with this form:
my $res = $ua->patch( $url, $field_name => $value, Content => $content );

# Using hash or array references requires HTTP::Message >= 6.12
use HTTP::Request 6.12;
my $res = $ua->patch( $url, \%form );
my $res = $ua->patch( $url, \@form );
my $res = $ua->patch( $url, \%form, $field_name => $value, ... );
my $res = $ua->patch( $url, $field_name => $value, Content => \%form );
my $res = $ua->patch( $url, $field_name => $value, Content => \@form );

This method will dispatch a PATCH request on the given URL, with %form or @form providing the key/value pairs for the fill-in form content. Additional headers and content options are the same as for the "get" in LWP::UserAgent method.

CAVEAT:

This method can only accept content that is in key-value pairs when using HTTP::Request::Common prior to version 6.12. Any use of hash or array references will result in an error prior to version 6.12.

This method will use the PATCH function from HTTP::Request::Common to build the request. See HTTP::Request::Common for a details on how to pass form content and other advanced features.

post

my $res = $ua->post( $url, \%form );
my $res = $ua->post( $url, \@form );
my $res = $ua->post( $url, \%form, $field_name => $value, ... );
my $res = $ua->post( $url, $field_name => $value, Content => \%form );
my $res = $ua->post( $url, $field_name => $value, Content => \@form );
my $res = $ua->post( $url, $field_name => $value, Content => $content );

This method will dispatch a POST request on the given URL, with %form or @form providing the key/value pairs for the fill-in form content. Additional headers and content options are the same as for the "get" in LWP::UserAgent method.

This method will use the POST function from HTTP::Request::Common to build the request. See HTTP::Request::Common for a details on how to pass form content and other advanced features.

put

# Any version of HTTP::Message works with this form:
my $res = $ua->put( $url, $field_name => $value, Content => $content );

# Using hash or array references requires HTTP::Message >= 6.07
use HTTP::Request 6.07;
my $res = $ua->put( $url, \%form );
my $res = $ua->put( $url, \@form );
my $res = $ua->put( $url, \%form, $field_name => $value, ... );
my $res = $ua->put( $url, $field_name => $value, Content => \%form );
my $res = $ua->put( $url, $field_name => $value, Content => \@form );

This method will dispatch a PUT request on the given URL, with %form or @form providing the key/value pairs for the fill-in form content. Additional headers and content options are the same as for the "get" in LWP::UserAgent method.

CAVEAT:

This method can only accept content that is in key-value pairs when using HTTP::Request::Common prior to version 6.07. Any use of hash or array references will result in an error prior to version 6.07.

This method will use the PUT function from HTTP::Request::Common to build the request. See HTTP::Request::Common for a details on how to pass form content and other advanced features.

request

my $res = $ua->request( $request );
my $res = $ua->request( $request, $content_file );
my $res = $ua->request( $request, $content_cb );
my $res = $ua->request( $request, $content_cb, $read_size_hint );

This method will dispatch the given $request object. Normally this will be an instance of the HTTP::Request class, but any object with a similar interface will do. The return value is an HTTP::Response object.

The request method will process redirects and authentication responses transparently. This means that it may actually send several simple requests via the "simple_request" in LWP::UserAgent method described below.

The request methods described above; "get" in LWP::UserAgent, "head" in LWP::UserAgent, "post" in LWP::UserAgent and "mirror" in LWP::UserAgent will all dispatch the request they build via this method. They are convenience methods that simply hide the creation of the request object for you.

The $content_file, $content_cb and $read_size_hint all correspond to options described with the "get" in LWP::UserAgent method above. Note that errors writing to the content file (for example due to permission denied or the filesystem being full) will be reported via the Client-Aborted or X-Died response headers, and not the is_success method.

You are allowed to use a CODE reference as content in the request object passed in. The content function should return the content when called. The content can be returned in chunks. The content function will be invoked repeatedly until it return an empty string to signal that there is no more content.

simple_request

my $request = HTTP::Request->new( ... );
my $res = $ua->simple_request( $request );
my $res = $ua->simple_request( $request, $content_file );
my $res = $ua->simple_request( $request, $content_cb );
my $res = $ua->simple_request( $request, $content_cb, $read_size_hint );

This method dispatches a single request and returns the response received. Arguments are the same as for the "request" in LWP::UserAgent described above.

The difference from "request" in LWP::UserAgent is that simple_request will not try to handle redirects or authentication responses. The "request" in LWP::UserAgent method will, in fact, invoke this method for each simple request it sends.

CALLBACK METHODS

The following methods will be invoked as requests are processed. These methods are documented here because subclasses of LWP::UserAgent might want to override their behaviour.

get_basic_credentials

# This checks wantarray and can either return an array:
my ($user, $pass) = $ua->get_basic_credentials( $realm, $uri, $isproxy );
# or a string that looks like "user:pass"
my $creds = $ua->get_basic_credentials($realm, $uri, $isproxy);

This is called by "request" in LWP::UserAgent to retrieve credentials for documents protected by Basic or Digest Authentication. The arguments passed in is the $realm provided by the server, the $uri requested and a boolean flag to indicate if this is authentication against a proxy server.

The method should return a username and password. It should return an empty list to abort the authentication resolution attempt. Subclasses can override this method to prompt the user for the information. An example of this can be found in lwp-request program distributed with this library.

The base implementation simply checks a set of pre-stored member variables, set up with the "credentials" in LWP::UserAgent method.

prepare_request

$request = $ua->prepare_request( $request );

This method is invoked by "simple_request" in LWP::UserAgent. Its task is to modify the given $request object by setting up various headers based on the attributes of the user agent. The return value should normally be the $request object passed in. If a different request object is returned it will be the one actually processed.

The headers affected by the base implementation are; User-Agent, From, Range and Cookie.

progress

my $prog = $ua->progress( $status, $request_or_response );

This is called frequently as the response is received regardless of how the content is processed. The method is called with $status "begin" at the start of processing the request and with $state "end" before the request method returns. In between these $status will be the fraction of the response currently received or the string "tick" if the fraction can't be calculated.

When $status is "begin" the second argument is the HTTP::Request object, otherwise it is the HTTP::Response object.

redirect_ok

my $bool = $ua->redirect_ok( $prospective_request, $response );

This method is called by "request" in LWP::UserAgent before it tries to follow a redirection to the request in $response. This should return a true value if this redirection is permissible. The $prospective_request will be the request to be sent if this method returns true.

The base implementation will return false unless the method is in the object's requests_redirectable list, false if the proposed redirection is to a file://... URL, and true otherwise.

BEST PRACTICES

The default settings can get you up and running quickly, but there are settings you can change in order to make your life easier.

Handling Cookies

You are encouraged to install Mozilla::PublicSuffix and use HTTP::CookieJar::LWP as your cookie jar. HTTP::CookieJar::LWP provides a better security model matching that of current Web browsers when Mozilla::PublicSuffix is installed.

use HTTP::CookieJar::LWP ();

my $jar = HTTP::CookieJar::LWP->new;
my $ua = LWP::UserAgent->new( cookie_jar => $jar );

See "cookie_jar" for more information.

Managing Protocols

protocols_allowed gives you the ability to allow arbitrary protocols.

my $ua = LWP::UserAgent->new(
    protocols_allowed => [ 'http', 'https' ]
);

This will prevent you from inadvertently following URLs like file:///etc/passwd. See "protocols_allowed".

protocols_forbidden gives you the ability to deny arbitrary protocols.

my $ua = LWP::UserAgent->new(
    protocols_forbidden => [ 'file', 'mailto', 'ssh', ]
);

This can also prevent you from inadvertently following URLs like file:///etc/passwd. See "protocols_forbidden".

SEE ALSO

See LWP for a complete overview of libwww-perl5. See lwpcook and the scripts lwp-request and lwp-download for examples of usage.

See HTTP::Request and HTTP::Response for a description of the message objects dispatched and received. See HTTP::Request::Common and HTML::Form for other ways to build request objects.

See WWW::Mechanize and WWW::Search for examples of more specialized user agents based on LWP::UserAgent.

COPYRIGHT AND LICENSE

Copyright 1995-2009 Gisle Aas.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

www-mechanize's People

Contributors

chorny avatar dakkar avatar dependabot[bot] avatar dsteinbrunner avatar epa avatar fany avatar ferki avatar gquipster avatar haarg avatar hercynium avatar jidanni avatar jmadler avatar karenetheridge avatar kyzn avatar manwar avatar neilb avatar oalders avatar obra avatar petdance avatar polettix avatar rjbs avatar sergeyromanov avatar shadowcat-mst avatar simbabque avatar sjohnston avatar skaji avatar sunnavy avatar szabgab avatar varadinsky avatar weirdtangent avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

www-mechanize's Issues

nonsensical credentials test [rt.cpan.org #103070]

Migrated from rt.cpan.org#103070 (status was 'new')

Requestors:

From [email protected] on 2015-03-24 17:37:21:

In WWW-Mechanize's t/credentials-api.t there's this test:

my @ua = $ua->credentials;
isnt( "@ua", "mech2 mech2", 'LWP::UserAgent instance retains its old credentials' );

This looks nonsensical.  The ->credentials method on LWP::UserAgent
isn't documented as being callable with no arguments, and indeed the
lack of arguments is causing a runtime warning:

t/credentials-api.t ...... Use of uninitialized value in lc at /opt/perl-5.20.2/lib/site_perl/5.20.2/LWP/UserAgent.pm line 606.
t/credentials-api.t ...... ok   

Presumably the call ought to include $netloc and $realm parameters
matching whatever the WWW::Mechanize objects are doing.

-zefram

Mention format of dump_forms

At
$mech->dump_forms( [$fh] )
Prints a dump of the forms on the current page to $fh. If $fh is not
specified or is undef, it dumps to STDOUT.

Please also mention the format of the dump, e.g., "ad-hoc".

Allow assigning to current_form();

   $mech->current_form()
       Returns the current form as an HTML::Form object.

is a one way street. One should also be able to set the current form
to an arbitrary HTML::Form object too.

select() has no way to access 2nd input of same name, nor recognize newer "multiple"

$mech->field( $name, $value, $number ) offers $number, but
$mech->select($name, $value) neglects it, causing e.g.,

    <dl>
      <dt><label for="user_profile_interest_tags">My Interests</label></dt>
      <dd class="with-icon">
        <span aria-hidden="true" data-icon="&#xe906;"
        class="icon mod-tag"></span>
        <input name="user_profile[interest_tags][]" type="hidden" value="" /><select data-interest-tags="true" id="user_profile_interest_tags" multiple="multiple" name="user_profile[interest_tags][]" placeholder="Add tags here to find places and people who share your interests!"><option selected="selected" value="vegan">vegan</option>
<option selected="selected" value="transgender">transgender</option>
<option selected="selected" value="maps">maps</option>
<option selected="selected" value="crossdressing">crossdressing</option>
<option selected="selected" value="bdsm">bdsm</option>
<option selected="selected" value="皮繩愉虐邦">皮繩愉虐邦</option></select>
      </dd>
    </dl>

to give Input "user_profile[interest_tags][]" is not type "select"
as there is no way to access the second similarly name input.

Require minimum version of Test::Builder

The Test::Builder that comes with MacOSX Sierra 10.12.2 causes the t/dump.t test in WWW::Mechanize to fail. Updating Test::Builder to the latest (1.302075) fixes this problem.

$ perl -T -Iblib/lib t/dump.t 
1..6
ok 1 - use WWW::Mechanize;
    1..5
    ok 1 - The object isa WWW::Mechanize
    ok 2 - Fetched file:///Users/pkrawczyk/.cpan/build/WWW-Mechanize-1.83-lF3nBv/t/find_inputs.html
    ok 3 - Dump file created
    ok 4 - Dump has valid values
    ok 5 - Valid STDOUT
ok 2 - dump_headers
    ok 1 - The object isa WWW::Mechanize
    ok 2 - Fetched file:///Users/pkrawczyk/.cpan/build/WWW-Mechanize-1.83-lF3nBv/
Use of uninitialized value $method in method lookup at t/dump.t line 132.
Can't locate object method "" via package "WWW::Mechanize" at t/dump.t line 132.
    # Child (dump_links test) exited without calling finalize()
not ok 3 - dump_links test
#   Failed test 'dump_links test'
#   at /System/Library/Perl/5.18/Test/Builder.pm line 252.
# Looks like you planned 6 tests but ran 3.
# Looks like you failed 1 test of 3 run.
# Looks like your test exited with 255 just after 3.

Please require a minimum version of Test::Builder greater than 0.98.

Alternately, please rewrite the test to not use the subtest method in its current form.

Warns when control is outside form tag even though it is legal [rt.cpan.org #26685]

Migrated from rt.cpan.org#26685 (status was 'open')

Requestors:

From [email protected] on 2007-04-26 02:40:13:

In the latest HTML::Form you have the ability to disable the warning
messages by not passing option verbose, however if you do it still
throws warnings if controls are found outside a form tag.  This is legal
HTML for at a minimum HTML 4.01 Transitional. following test script
fails on warnings against a valid HTML 4.01 transitional page:

use strict;

use Test::More tests => 2;
use Test::NoWarnings;

use_ok('HTML::Form');


#Valid HTML
my $html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'
          .'<html><head><title>No Warnings</title></head><body>'
          ."<select OnChange='location.href=\"index.php?"
          ."foo=\"+this.value'>"
          ."<OPTION value='bar'>bar</OPTION>"
          ."</body>";

#Shouldn't throw any warnings on valid HTML
my $form = HTML::Form->parse($html,'http://example.com');

Throws the following warning:
Carp::carp('<option> outside <form>') called at
/usr/local/lib/perl5/site_perl/5.6.1/HTML/Form.pm line 114


Perl 5.6.1 on FreeBSD 4.8-RELEASE-p17 

From [email protected] on 2017-01-25 21:37:21:

migrated queue: libwww-perl -> WWW-Mechanize

Use scalar refs to select options?

I'm not sure this is a Mech issue, nor how feasible it is, but I got lost in the code and had to abort when I tried.

It would be neat if scalar references could select options when submitting forms, by selecting that numbered option.

$mech->submit_form(
  with_fields => {
    select_box => \2
  }
);

This would choose the second <option> in the form, irrespective of its value.

Document how to see what will be sent without actually sending anything

I did it! I figured out how to show what will be sent on a request
without actually sending anything!

use WWW::Mechanize;
my $mech = WWW::Mechanize->new();
$mech->add_handler("request_send", sub { shift->dump; exit; });
$mech->get("http://www.example.com");

(Important when you don't want to create any suspicious traffic while
perfecting your program.) Please document it.

word stuck together on man page

$ man WWW::Mechanize|perl -nwle 'print for /\S+instances/g;'
WWW::Mechanizeinstances

Package: libwww-mechanize-perl
Version: 1.83-1

test failure: t\local\back.t line 53 [rt.cpan.org #106677]

Migrated from rt.cpan.org#106677 (status was 'new')

Requestors:

From [email protected] on 2015-08-26 16:29:28:

Via an email I received:

I wanted to install WWW::Mechanize on my new laptop and desktop. But I always got an error message �t\local\back.t����1/47 Error getting http://localhost:51288/:Can�t connect to  localhost:51288 at t\local\back.t line 53� . I tried many times and still cannot pass from this line. I actually installed this module at my old laptop and it worked perfect. But it was very long time ago and must be an old version of this module. Do you know how to solve this problem? Maybe it is a bug in this new 1.75 version? Thank you very much!!!

mention what if more than one form_width() match

The warning of

   $mech->form_with_fields( @fields )
       Selects a form by passing in a list of field names it must contain.  If
       there is more than one form on the page with that matches, then the
       first one is used, and a warning is generated.

should also be mentioned on

   $mech->form_with( $attr1 => $value1, $attr2 => $value2, ... )

if indeed that is also the case.

Live test can't lookup del.icio.us

This seems to be an intermittent failure, but very frustrating when trying to build a Docker container as it requires starting from scratch. Must it cast out to the wider internet?

Mention what does not get clone()ed

In the man page at $mech->clone, mention that handlers are apparently
not cloned so one needs to do e.g.,

$mech->add_handler( "request_send", sub { shift->dump; exit; } );
my $mech2  = $mech->clone();
$mech2->add_handler( "request_send", sub { shift->dump; exit; } ); #first one gone

Maybe there are more things not cloned too... Do mention them all
there please.

Forgot submit_form( form=> HTML::Form_object) !

Let's say there are plenty of forms on a page and they all are quite
similar, so it turns out the only way to pinpoint the exact one we
want is e.g.,

my $form = ($mech->all_forms_with_fields(qw/confirm ignore block/))[3];

OK we got our form. Alas, we cannot use it because can you believe
there is no way to set a given HTML::Form object that we found on the
page as the current form. Nor can we use

$mech->submit_form( ... )
       o   "fields => \%fields"
       o   "with_fields => \%fields"
       o   "form_number => n"
       o   etc.

is missing

       o   "form" => \$HTML::Form object

That's right, the authors just assume that they have all the ways to
select the current form covered, so they forgot the trump card needed
for the universal case. Or at least the WWW::Mechanize man page
doesn't say how. Apparently one must use $mech->post( $url, \%form )
directly...

OK here's the workaround,

my $target_form =
  ( $mech->all_forms_with_fields(qw/confirm ignore block/) )[3];
die unless $target_form;
my $c;
for ( $mech->forms() ) {
    $c++;
    if ( $_ eq $target_form ) {
        $mech->form_number($c);
        last;
    }
}
die unless $mech->current_form() eq $target_form;    #double check

Geeez.

Say $mech->submit submits current form, not "the page"

Don't you mean "Submits the CURRENT FORM" not "the page"?

=head2 $mech->submit()

Submits the page, without specifying a button to click. Actually,
no button is clicked at all.
...
my $request = $self->current_form->make_request;

Error GETing https://del.icio.us/ (1.81)

On smoker systems without LWP::Protocol::https installed I see the following failure:

Error GETing https://del.icio.us/: Protocol scheme 'https' is not supported (LWP::Protocol::https not installed) at t/live/encoding.t line 26.
# Tests were run but no plan was declared and done_testing() was not seen.
# Looks like your test exited with 2 just after 2.
t/live/encoding.t ........ 
Dubious, test returned 2 (wstat 512, 0x200)
All 2 subtests passed 

Bad Test, "t/local/failure.t", tries to look up an existing domain, not a "non-existing one" as it states.

Installed WWW::Mechanize-1.83.
It failed to run the above bad test, because it does a bad test for an existing domain.
It runs:
my $NONEXISTENT = 'blahblahblah.xx-only-testing.foo';
my @results = gethostbyname( $NONEXISTENT );
Test output:
t/local/failure.t .......... skipped: Your ISP is overly helpful and returns 10.0.0.1 for non-existent domain blahblahblah.xx-only-testing.foo. This test cannot be run.

Since the query doesn't append a dot (or period), the query is relative to the current domain and
correctly returns the external gateway address of the domain.

In order to look up a hostname with "foo" as the TLD, you need to append a period to the hostname in your call to gethostbyname. I.e.:

(note period after "foo")

my $NONEXISTENT = 'blahblahblah.xx-only-testing.foo.';

Cheers!

(update to use better IP example)

submit_form giving both form_number and with_fields

submit_form takes various filters such as form_number and with_fields. The synopsis in the pod documentation gives an example usage:

            $mech->submit_form(
                form_number => 3,
                fields      => {
                    username    => 'mungo',
                    password    => 'lost-and-alone',
                }
            );

(side buglet: this has fields instead of with_fields)

However, if with_fields is passed then any form_number argument is ignored; similarly if you pass form_number then form_name is ignored, and so on.

The behaviour that makes the most sense is to AND together the filters provided. In a way, that would be a backwards-incompatible change since there may be code in the wild that passes both form_number and with_fields and has come to rely on the fact that form_number is ignored in this case. So you might want to issue a warning (during a transitional period) if multiple filters are passed.

(Previously filed at https://code.google.com/p/www-mechanize/issues/detail?id=264 but that page is now broken)

Test hangs on perl: res_query.c:262: __libc_res_nquery: Assertion `(hp != ((void *)0)) && (hp2 != ((void *)0))' failed

If you try and build this on Debian Jessie, the test will produce an error:

perl: res_query.c:262: __libc_res_nquery: Assertion `(hp != ((void *)0)) && (hp2 != ((void *)0))' failed.

and will hang on the t/local/failure.t test.

backtraces here:
http://sprunge.us/OgfY

and
http://sprunge.us/XSgM

Thanks to TonyC for pointing me to a fix:
https://bbs.archlinux.org/viewtopic.php?pid=1607876#p1607876

On debian, temporarily disabling IPv6 solved my issue. with:

sudo sh -c 'echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6'

no way to avoid Wide character warnings with mech-dump

Often the user will get this error message

$ mech-dump https://m.facebook.com | head
Wide character in print at /usr/share/perl5/WWW/Mechanize.pm line 2223.
POST https://m.facebook.com/login.php?refsrc=https%3A%2F%2Fm.facebook.com%2F&lwv=100&refid=8
lsd=AVpaPweT (hidden readonly)
charset_test=€,´,€,´,水,Д,Є (hidden readonly)...

But there is nothing he can do about it, because all the binmode etc. stuff happens under the hood beyond his control.

libwww-mechanize-perl:
Installed: 1.75-1

missing value for field input with image as type [rt.cpan.org #44430]

Migrated from rt.cpan.org#44430 (status was 'open')

Requestors:

Attachments:

From [email protected] on 2009-03-19 22:24:17:

Hello,

Exists a bug, at list if this module follow the HTML4 specification and 
normal browsers, the problem is because don't send the specific value 
attribute of an input field that has image as type, when of course 
exists a name attribute.

Here's a discussion http://www.perlmonks.org/?node_id=751884

Cheers,
Michael

From [email protected] on 2009-06-15 16:39:50:

I created the attached patch but then decided that this behaviour is actually wrong so I did not 
really apply it to the master branch.  Do you have any more information about what browsers 
implement <input type=image> this way?

From [email protected] on 2017-01-25 21:37:32:

migrated queue: libwww-perl -> WWW-Mechanize

Is mirror() broken?

In two environments - FreeBSD and Linux - with different versions - 1.74 and 1.73 respectively - mirror produces a file with binary content. Changing the object to LWP::UserAgent produces the correct output (as does LWP::Simple.)

[rt.cpan.org #18962]

Migrated from rt.cpan.org#18962 (status was 'open')

Requestors:

Attachments:

From [email protected] on 2006-04-28 01:16:10:


From [email protected] on 2006-04-28 01:45:08:

value() does not work but param() does.  param() takes the trouble to go
through each possible input.  Here's an updated test.


From on 2006-07-02 21:04:27:

Just adding to the point of the about the needlessness of the checking
of the possible values.  A very practical case for not checking the
values is testing some web application using HTML::Form against various
user input.

From [email protected] on 2017-01-25 21:37:03:

migrated queue: libwww-perl -> WWW-Mechanize

Convert to Dist::Zilla

As it stands, the test suite is broken. It's easy stuff that could be managed by Dist::Zilla. Unless anyone objects in the next couple of days, I'll convert to dzil.

Don't assume unique parameter names

This assumes there will never be multiple parameters with the same name. Perfectly legal in e.g.,
this URL from Google Static Maps API.

 my $fields;
    for (qw/with_fields fields/) {
        if ($args{$_}) {
            if ( ref $args{$_} eq 'HASH' ) {
                $fields = $args{$_};
            }
            else {
                die "$_ arg to submit_form must be a hashref";
            }
            last;
        }
    }

provide a means to inspect history

The mech docs say:

Mech also stores a history of the URLs you've visited, which can
be queried and revisited.

This is a pretty big overstatement. The only real access to history is ->back.

I propose to add a method $mech->history($n) which will return the nth history item since current. If $n is zero, it will return the most recent history item, and otherwise it will index -$n into the history stack.

The history item will be returned as a hashref like this: { req => $http_req, res => $http_res }

I will also add $mech->history_count which will be the number of items in history. That way, you could iterate (0 .. $history_count - 1) for all useful values to pass to ->history.

If this sounds good, I will write a patch.

Tests fail under Windows [rt.cpan.org #105241]

Migrated from rt.cpan.org#105241 (status was 'new')

Requestors:

From [email protected] on 2015-06-15 16:11:59:

Hi,

several of the tests (12 of the 39 test scripts) fail under Windows, because the modules don't find their DLLs via the ("sanitized") PATH. 

As an example I run add_header.t manually:


D:\tmp\strawberry-5.20-64\archive\WWW-Mechanize-1.74>perl -T t\add_header.t
1..4
ok 1 - use WWW::Mechanize;
Can't load 'c:/strawberry-5.20.2.1-64/perl/vendor/lib/auto/Net/SSLeay/SSLeay.xs.dll' for module Net::SSLeay: load_file:Das angegebene Modul wurde nicht gefunden
 at c:/strawberry-5.20.2.1-64/perl/lib/DynaLoader.pm line 193.
 at c:/strawberry-5.20.2.1-64/perl/vendor/lib/IO/Socket/SSL.pm line 19.
Compilation failed in require at c:/strawberry-5.20.2.1-64/perl/vendor/lib/IO/Socket/SSL.pm line 19.
BEGIN failed--compilation aborted at c:/strawberry-5.20.2.1-64/perl/vendor/lib/IO/Socket/SSL.pm line 19.
Compilation failed in require at c:/strawberry-5.20.2.1-64/perl/vendor/lib/Net/HTTPS.pm line 26.
Can't load 'c:/strawberry-5.20.2.1-64/perl/vendor/lib/auto/Crypt/SSLeay/SSLeay.xs.dll' for module Crypt::SSLeay: load_file:Das angegebene Modul wurde nicht gefunden at c:/strawberry-5.20.2.1-64/perl/lib/DynaLoader.pm line 193.
 at c:/strawberry-5.20.2.1-64/perl/vendor/lib/Net/SSL.pm line 20.
Compilation failed in require at c:/strawberry-5.20.2.1-64/perl/vendor/lib/Net/SSL.pm line 20.
Compilation failed in require at c:/strawberry-5.20.2.1-64/perl/vendor/lib/Net/HTTPS.pm line 30.
Compilation failed in require at c:/strawberry-5.20.2.1-64/perl/vendor/lib/LWP/Protocol/https.pm line 8.
Compilation failed in require at (eval 26) line 2.

# Looks like you planned 4 tests but ran 1.
# Looks like your test exited with 2 just after 1.



Together with the "Can't load 'c:/.../SSLeay.xs.dll'" I also got a Windows error dialog, telling me LIBEAY32__.dll is missing on my Computer and I have to 'reinstall the program'. That means, SSLeay.xs.dll exists, but can't be loaded, because LIBEAY32__.dll isn't found by the Windows DLL loader.

C:\strawberry-5.20-64\c\bin\libeay32__.dll exists and C:\strawberry-5.20-64\c\bin\ is in the %PATH%.



When I change the code of t\add_header.t from

BEGIN {
    delete @ENV{qw( PATH IFS CDPATH ENV BASH_ENV )};  # Placates taint-unsafe Cwd.pm in 5.6.1
    use_ok( 'WWW::Mechanize' );
}

to

BEGIN {
    delete @ENV{qw( IFS CDPATH ENV BASH_ENV )};  # Placates taint-unsafe Cwd.pm in 5.6.1
    use_ok( 'WWW::Mechanize' );
}



everything is ok:



D:\tmp\strawberry-5.20-64\archive\WWW-Mechanize-1.74>perl -T t\add_header.t
1..4
ok 1 - use WWW::Mechanize;
ok 2 - 'Created agent' isa 'WWW::Mechanize'
ok 3 - Referer's in there
ok 4 - Referer's not there


Ralf

No way to grow selection list

Man page says

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

Alas there is no way to grow the list from e.g., six slots to nine.
And by adding you mean overwriting.

Failed dump_links test (due to runtime error) during cpanm install on Ubuntu 10.04.4, perl v5.20.0

WWW-Mechanize-1.83

Full build log

Relevant error:

Use of uninitialized value $method in method lookup at t/dump.t line 132.
Can't locate object method "" via package "WWW::Mechanize" at t/dump.t line 132.
    # Child (dump_links test) exited without calling finalize()

#   Failed test 'dump_links test'
#   at /opt/perlbrew/perls/perl-5.20.0/lib/5.20.0/Test/Builder.pm line 276.
# Looks like you planned 6 tests but ran 3.
# Looks like you failed 1 test of 3 run.
# Looks like your test exited with 255 just after 3.
t/dump.t ................... 
Dubious, test returned 255 (wstat 65280, 0xff00)
Failed 4/6 subtests 

Fails to get action URL correct on self referring https form

Trying to submit the login form https://www.domainmonster.com/login/ but WWW::Mechanize (v1.75) gets the protocol wrong

$ mech-dump https://www.domainmonster.com/login/ | grep POST
POST http://www.domainmonster.com:443/login/
POST https://www.domainmonster.com/register/

Note the http instead of https on the first form but it does seem to get the second (non-self-referring) one correct.

HTML::Form gets the correct action

#!/usr/bin/env perl
use strict;
use warnings;

use HTML::Form;
my $f=HTML::Form->parse (qq!
<form action="/login/" method="post" id="login">
    <input type="hidden" name="action" id="action" value="dologin" />
    <br style="clear:both;" />
        <dl>
                <img src="/images/login/login-mbr-mnstr.png" alt="login now" class="monsterlog">
        <dt>Email Address:</dt><dd><input type="text" name="username" id="username" class="inLng" /></dd>
        <dt>Password:</dt><dd><input type="password" name="password" id="password"  class="inMid" autocomplete="off" /></dd>
        </dl>
        <p>Please note that passwords are case-sensitive.</p>
        <p><input type="submit" value="" class="loginSubmitButton" /></p>
        </form>
!,"https://www.domainmonster.com/login/");

my $a=$f->action;
print "Action - $a\n";

Prints

Action - https://www.domainmonster.com/login/

As expected

Obviously, this issue stops the form submission working unless I manually fix the action in the form to the right URL

HTML::Form does not work well with Mechanize response objects [rt.cpan.org #54233]

Migrated from rt.cpan.org#54233 (status was 'open')

Requestors:

From [email protected] on 2010-02-02 21:19:50:

The below code tends to work with response objects from LWP::Useragent, 
however for WWW::Mechanize response object, it simply throws an error 

"HTML::Form::parse: No $base_uri provided at ./test.pl line 49"

--------------Sample-Code-------------------------------
my $forms = HTML::Form->parse( "$formresponse" );
my $value = $forms->find_input('SetShift')->value;
print $value;
\\-----------Sample-Code-----------------------------\\

Moreover "$forms->attr( 'SetShift' )" does not seem to be a shortcut to 
saying "$forms->find_input('SetShift')->value" as mentioned in the 
documentation. 

From [email protected] on 2017-01-25 21:37:33:

migrated queue: libwww-perl -> WWW-Mechanize

Calling $mech->uri on a new Mech object should not crash

If there's no response object yet, such as if the Mech is brand new, I suggest that $mech->uri should return undef.

$ cat foo.pl
use strict;
use warnings;
use 5.010;

use WWW::Mechanize;

say 'Running v', $WWW::Mechanize::VERSION;

my $mech = WWW::Mechanize->new();
my $uri = $mech->uri;
$ perl foo.pl
Running v1.75
Can't call method "request" on an undefined value at /var/perl5.20.3/lib/site_perl/5.20.3/WWW/Mechanize.pm line 553.

mention form_with_fields prints warning if no such field found

$mech->form_with_fields( @fields )

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

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

   Returns undef if no form is found.

And also prints a warning!

Tests hang on Win32

In case someone is wondering why there are no cpantester reports for 1.75 with Perl 5.22 on Windows: The reason is that the test suite hangs until it is killed by some timeout:

Running make test
"C:\strawberry\perl\bin\perl.exe" "-MExtUtils::Command::MM" "-MTest::Harness" "-
e" "undef *Test::Harness::Switches; test_harness(0, 'blib\lib', 'blib\arch')" t\
00-load.t t\add_header.t t\aliases.t t\area_link.t t\autocheck.t t\clone.t t\con
tent.t t\cookies.t t\credentials-api.t t\credentials.t t\die.t t\dump.t t\field.
t t\find_frame.t t\find_image.t t\find_inputs.t t\find_link-warnings.t t\find_li
nk.t t\find_link_id.t t\form-parsing.t t\form_with_fields.t t\frames.t t\image-n
ew.t t\image-parse.t t\link-base.t t\link-relative.t t\link.t t\new.t t\pod-cove
rage.t t\pod.t t\regex-error.t t\save_content.t t\select.t t\taint.t t\tick.t t\
untaint.t t\upload.t t\warn.t t\warnings.t t\local\back.t t\local\click.t t\loca
l\click_button.t t\local\content.t t\local\encoding.t t\local\failure.t t\local\
follow.t t\local\form.t t\local\get.t t\local\nonascii.t t\local\overload.t t\lo
cal\page_stack.t t\local\referer.t t\local\reload.t t\local\submit.t t\mech-dump
\mech-dump.t
# Testing WWW::Mechanize 1.75, with LWP 6.13, Perl 5.022000, C:\strawberry\perl\
bin\perl.exe
# Test::Memory::Cycle is not installed.
t\00-load.t .............. ok
t\add_header.t ........... ok
t\aliases.t .............. ok
t\area_link.t ............ ok
t\autocheck.t ............ ok
t\clone.t ................ ok
t\content.t .............. ok
t\cookies.t .............. skipped: HTTP::Server::Simple does not support Window
s yet.
t\credentials-api.t ...... ok
t\credentials.t .......... ok
t\die.t .................. ok
t\dump.t ................. ok
t\field.t ................ ok
t\find_frame.t ........... ok
t\find_image.t ........... ok
t\find_inputs.t .......... ok
t\find_link-warnings.t ... ok
t\find_link.t ............ ok
t\find_link_id.t ......... ok
t\form-parsing.t ......... ok
There are 2 forms with the named fields.  The first one was used. at t\form_with
_fields.t line 27.
t\form_with_fields.t ..... ok
t\frames.t ............... ok
t\image-new.t ............ ok
t\image-parse.t .......... ok
t\link-base.t ............ ok
t\link-relative.t ........ ok
t\link.t ................. ok
Error GETing http://localhost:1473/: Can't connect to localhost:1473 at t\local\
back.t line 53.

This makes Mech 1.75 more or less uninstallable on Windows.

Repeadly calling `->reload` leads to "request too large" if there are cookies

Relevant facs:

  • LWP::UserAgent sets up a request_prepare handler that calls $self->cookie_jar->add_cookie_header($req)
  • HTTP::Cookies::add_cookie_header always preserves existing cookies in a request object
  • WWW::Mechanize::reload calls $self->request($self->{req})

As a consequence, for every reload, the length of the Cookie header increases, until the server refuses to fulfil the request.

It can be argued that HTTP::Cookies should merge existing cookies, not just add. I'll be sending a bug report for that module, as well.

In the meantime, a simple workaround in WWW::Mechanize is:

sub reload {
    my $self = shift;

    return unless my $req = $self->{req};
    $req->remove_header('Cookie');

    return $self->_update_page( $req, $self->_make_request( $req, @_ ) );
}

Hope this helps.

mech-dump --all should add a title to each section of output

$ man mech-dump
--all Dump all four of the above, in that order

Well OK, but in the output you should say
headers:
....
forms:
....
links:
.....
images:
....

else it is hard to tell them apart sometimes.

Always have all four titles too, even if only three are present.

libwww-mechanize-perl:
Installed: 1.75-1

Allow selecting the nth matching form

Functions like

   $mech->form_with_fields( @fields )
       Selects a form by passing in a list of field names it must contain.  If
       there is more than one form on the page with that matches, then the
       first one is used, and a warning is generated.

just "assume" we only want the first matching form. As far as the 2nd
etc. matches, well it will just generate a warning about that.

It really needs an additional parameter, nth, in case the user wants
a match different that the first. For which alas he is currently out
of luck.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.