home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Perl_Libs / site_perl / HTML / LinkExtor.pm < prev    next >
Text File  |  1997-12-05  |  5KB  |  186 lines

  1. package HTML::LinkExtor;
  2.  
  3. =head1 NAME
  4.  
  5. HTML::LinkExtor - Extract links from an HTML document
  6.  
  7. =head1 SYNOPSIS
  8.  
  9.  require HTML::LinkExtor;
  10.  $p = HTML::LinkExtor->new(\&cb, "http://www.sn.no/");
  11.  sub cb {
  12.      my($tag, %links) = @_;
  13.      print "$tag @{[%links]}\n";
  14.  }
  15.  $p->parse_file("index.html");
  16.  
  17. =head1 DESCRIPTION
  18.  
  19. The I<HTML::LinkExtor> (link extractor) is an HTML parser that takes a
  20. callback routine as parameter.  This routine is then called as the
  21. various link attributes are recognized.
  22.  
  23. The I<HTML::LinkExtor> is a subclass of I<HTML::Parser>. This means
  24. that the document should be given to the parser by calling the
  25. $p->parse() or $p->parse_file() methods.
  26.  
  27. =cut
  28.  
  29. require HTML::Parser;
  30. @ISA = qw(HTML::Parser);
  31.  
  32. use URI::URL qw(url);
  33.  
  34. use strict;
  35. use vars qw(%LINK_ELEMENT);
  36.  
  37. # Elements that might contain links and the name of the link attribute
  38. %LINK_ELEMENT =
  39. (
  40.  body   => 'background',
  41.  base   => 'href',
  42.  a      => 'href',
  43.  img    => [qw(src lowsrc usemap)],   # 'lowsrc' is a Netscape invention
  44.  form   => 'action',
  45.  input  => 'src',
  46. 'link'  => 'href',          # need quoting since link is a perl builtin
  47.  frame  => 'src',
  48.  applet => [qw(codebase code)],
  49.  area   => 'href',
  50.  frame  => 'src',   # Netscape 2.0 extention
  51.  embed  => 'src',   # used in Netscape 2.0 for Shockwave and things like that
  52. );
  53.  
  54. =over 4
  55.  
  56. =item $p = HTML::LinkExtor->new([$callback[, $base]])
  57.  
  58. The constructor takes two optional argument. The first is a reference
  59. to a callback routine. It will be called as links are found. If a
  60. callback is not provided, then links are just accumulated internally
  61. and can be retrieved by calling the $p->links() method. The $base is
  62. an optional base URL used to absolutize all URLs found.
  63.  
  64. The callback is called with the lowercase tag name as first argument,
  65. and then all link attributes as separate key/value pairs.  All
  66. non-link attributes are removed.
  67.  
  68. =cut
  69.  
  70. sub new
  71. {
  72.     my($class, $cb, $base) = @_;
  73.     my $self = $class->SUPER::new;
  74.     $self->{extractlink_cb} = $cb;
  75.     $self->{extractlink_base} = $base;
  76.     $self;
  77. }
  78.  
  79. sub start
  80. {
  81.     my($self, $tag, $attr) = @_;  # $attr is reference to a HASH
  82.     return unless exists $LINK_ELEMENT{$tag};
  83.  
  84.     my $base = $self->{extractlink_base};
  85.     my $links = $LINK_ELEMENT{$tag};
  86.     $links = [$links] unless ref $links;
  87.  
  88.     my @links;
  89.     my $a;
  90.     for $a (@$links) {
  91.     next unless exists $attr->{$a};
  92.     push(@links, $a, $base ? url($attr->{$a}, $base)->abs : $attr->{$a});
  93.     }
  94.     return unless @links;
  95.  
  96.     my $cb = $self->{extractlink_cb};
  97.     if ($cb) {
  98.     &$cb($tag, @links);
  99.     } else {
  100.     push(@{$self->{'links'}}, [$tag, @links]);
  101.     }
  102. }
  103.  
  104. =item $p->links
  105.  
  106. Returns a list of all links found in the document.  The returned
  107. values will be anonymous arrays with the follwing elements:
  108.  
  109.   [$tag, $attr => $url1, $attr2 => $url2,...]
  110.  
  111. The $p->links method will also truncate the internal link list.  This
  112. means that if the method is called twice without any parsing in
  113. between then the second call will return an empty list.
  114.  
  115. Also note that $p->links will always be empty if a callback routine
  116. was provided when the L<HTML::LinkExtor> was created.
  117.  
  118. =cut
  119.  
  120. sub links
  121. {
  122.     my $self = shift;
  123.     exists($self->{'links'}) ? @{delete $self->{'links'}} : ();
  124. }
  125.  
  126. # We override the parse_file() method so that we can clear the links
  127. # before we start with a new file.
  128. sub parse_file
  129. {
  130.     my $self = shift;
  131.     delete $self->{'links'};
  132.     $self->SUPER::parse_file(@_);
  133. }
  134.  
  135. =back
  136.  
  137. =head1 EXAMPLE
  138.  
  139. This is an example showing how you can extract links as a document
  140. is received using LWP:
  141.  
  142.   use LWP::UserAgent;
  143.   use HTML::LinkExtor;
  144.   use URI::URL;
  145.  
  146.   $url = "http://www.sn.no/";  # for instance
  147.   $ua = new LWP::UserAgent;
  148.  
  149.   # Set up a callback that collect image links
  150.   my @imgs = ();
  151.   sub callback {
  152.      my($tag, %attr) = @_;
  153.      return if $tag ne 'img';  # we only look closer at <img ...>
  154.      push(@imgs, values %attr);
  155.   }
  156.  
  157.   # Make the parser.  Unfortunately, we don't know the base yet
  158.   # (it might be diffent from $url)
  159.   $p = HTML::LinkExtor->new(\&callback);
  160.  
  161.   # Request document and parse it as it arrives
  162.   $res = $ua->request(HTTP::Request->new(GET => $url),
  163.                       sub {$p->parse($_[0])});
  164.  
  165.   # Expand all image URLs to absolute ones
  166.   my $base = $res->base;
  167.   @imgs = map { $_ = url($_, $base)->abs; } @imgs;
  168.  
  169.   # Print them out
  170.   print join("\n", @imgs), "\n";
  171.  
  172. =head1 SEE ALSO
  173.  
  174. L<HTML::Parser>
  175.  
  176. =head1 COPYRIGHT
  177.  
  178. Copyright 1996-1997 Gisle Aas.
  179.  
  180. This library is free software; you can redistribute it and/or
  181. modify it under the same terms as Perl itself.
  182.  
  183. =cut
  184.  
  185. 1;
  186.