Perl WWW :: Mechanize as a child class; cannot remain included in the scraper site

I have a simple login script using Perl WWW :: Mechanize. I write scripts in Moodle . When I just follow the login steps as procedural steps, it works. For example (suppose $ site_url, USERNAME, and PASSWORD were set respectively):

#THIS WORKS
$updater->get("http://".$site_url."/login/index.php");
$updater->form_id("login");
$updater->field('username', USERNAME);
$updater->field('password', PASSWORD);
$updater->click();
$updater->get("http://".$site_url."/");
print $updater->content();

When I try to encapsulate these steps inside the WWW child class: Mechanize, the get () and content () methods and other methods seem to work, but the site is not logged in. I have a feeling that it is associated with a variable scope, but I do not know how to resolve it.

Example (failure):

my $updater = new AutoUpdater( $site_url, USERNAME, PASSWORD );
$updater->do_login();

{
package AutoUpdater;
use base qw( WWW::Mechanize );

sub new {
    my $class = shift;
    my $self = {
        site_url => shift,
        USERNAME => shift,
        PASSWORD => shift,
   };
    bless $self, $class;
    return $self;
}

sub do_login {
    my $self = shift;
    $self->get("http://".$site_url."/");
    $self->get("http://".$site_url."/login/index.php");
    $self->form_id("login");
    $self->field("username", $self->{USERNAME});
    $self->field("password", $self->{PASSWORD});
    $self->click();
    $self->get("http://".$site_url."/");
    print $self->content();
}
}

. "Fail" , . -, HTML. . ! (, "yargh" )

!

+3
1

:

use strict;
use warnings;

my $updater = AutoUpdater->new( $site_url, USERNAME, PASSWORD );
$updater->do_login();

{
package AutoUpdater;
use parent qw( WWW::Mechanize );

sub new {
  my $class = shift;

  my $self = $class->SUPER::new();

  $self->{AutoUpdater} = {
    site_url => shift,
    USERNAME => shift,
    PASSWORD => shift,
  };

  return $self;
}

sub do_login {
  my $self = shift;
  my $data = $self->{AutoUpdater};

  $self->get("http://$data->{site_url}/login/index.php");
  $self->form_id("login");
  $self->field("username", $data->{USERNAME});
  $self->field("password", $data->{PASSWORD});
  $self->click();
  $self->get("http://$data->{site_url}/");
  print $self->content();
}
} # end package AutoUpdater

:

strict warnings, .

. Class->new new Class.

base pragma , . parent .

, Perl . $class->SUPER::new, .

, . Perl hashrefs, , hashref. , , hashref, . , . site_url, site_url - , . hashref ( , ), .

Moose OO Perl, -Moose , .

+2

All Articles