home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _897baef8e539961404f12f53eaba8c56 < prev    next >
Text File  |  2000-03-15  |  8KB  |  285 lines

  1. package HTML::TokeParser;
  2.  
  3. # $Id: TokeParser.pm,v 2.5 1999/06/09 10:20:02 gisle Exp $
  4.  
  5. require HTML::Parser;
  6. @ISA=qw(HTML::Parser);
  7. $VERSION = sprintf("%d.%02d", q$Revision: 2.5 $ =~ /(\d+)\.(\d+)/);
  8.  
  9. use strict;
  10. use Carp qw(croak);
  11. use HTML::Entities qw(decode_entities);
  12.  
  13.  
  14. sub new
  15. {
  16.     my $class = shift;
  17.     my $file = shift;
  18.     croak "Usage: $class->new(\$file)" unless defined $file;
  19.     if (!ref($file) && ref(\$file) ne "GLOB") {
  20.     require IO::File;
  21.     $file = IO::File->new($file, "r") || return;
  22.     }
  23.     my $self = $class->SUPER::new;
  24.     $self->{tokens} = [];
  25.     $self->{textify} = {img => "alt", applet => "alt"};
  26.     if (ref($file) eq "SCALAR") {
  27.     $self->parse($$file);
  28.     $self->eof;
  29.     } else {
  30.     $self->{file} = $file;
  31.     }
  32.     $self;
  33. }
  34.  
  35. # Set up callback methods
  36. for (qw(declaration start end text comment)) {
  37.     my $t = uc(substr($_,0,1));
  38.     no strict 'refs';
  39.     *$_ = sub { my $self = shift; push(@{$self->{tokens}}, [$t, @_]) };
  40. }
  41.  
  42.  
  43. sub get_token
  44. {
  45.     my $self = shift;
  46.     while (!@{$self->{tokens}} && $self->{file}) {
  47.     # must try to parse more of the file
  48.     my $buf;
  49.     if (read($self->{file}, $buf, 512)) {
  50.         $self->parse($buf);
  51.     } else {
  52.         $self->eof;
  53.         delete $self->{file};
  54.     }
  55.     }
  56.     shift @{$self->{tokens}};
  57. }
  58.  
  59.  
  60. sub unget_token
  61. {
  62.     my $self = shift;
  63.     unshift @{$self->{tokens}}, @_;
  64.     $self;
  65. }
  66.  
  67.  
  68. sub get_tag
  69. {
  70.     my $self = shift;
  71.     my $wanted = shift;
  72.     my $token;
  73.   GET_TOKEN:
  74.     {
  75.     $token = $self->get_token;
  76.     if ($token) {
  77.         my $type = shift @$token;
  78.         redo GET_TOKEN if $type !~ /^[SE]$/;
  79.         substr($token->[0], 0, 0) = "/" if $type eq "E";
  80.         redo GET_TOKEN if defined($wanted) && $token->[0] ne $wanted;
  81.     }
  82.     }
  83.     $token;
  84. }
  85.  
  86.  
  87. sub get_text
  88. {
  89.     my $self = shift;
  90.     my $endat = shift;
  91.     my @text;
  92.     while (my $token = $self->get_token) {
  93.     my $type = $token->[0];
  94.     if ($type eq "T") {
  95.         push(@text, decode_entities($token->[1]));
  96.     } elsif ($type =~ /^[SE]$/) {
  97.         my $tag = $token->[1];
  98.         if ($type eq "S") {
  99.         if (exists $self->{textify}{$tag}) {
  100.             my $alt = $self->{textify}{$tag};
  101.             my $text;
  102.             if (ref($alt)) {
  103.             $text = &$alt(@$token);
  104.             } else {
  105.             $text = $token->[2]{$alt || "alt"};
  106.             $text = "[\U$tag]" unless defined $text;
  107.             }
  108.             push(@text, $text);
  109.             next;
  110.         }
  111.         } else {
  112.         $tag = "/$tag";
  113.         }
  114.         if (!defined($endat) || $endat eq $tag) {
  115.          $self->unget_token($token);
  116.          last;
  117.         }
  118.     }
  119.     }
  120.     join("", @text);
  121. }
  122.  
  123.  
  124. sub get_trimmed_text
  125. {
  126.     my $self = shift;
  127.     my $text = $self->get_text(@_);
  128.     $text =~ s/^\s+//; $text =~ s/\s+$//; $text =~ s/\s+/ /g;
  129.     $text;
  130. }
  131.  
  132. 1;
  133.  
  134.  
  135. __END__
  136.  
  137. =head1 NAME
  138.  
  139. HTML::TokeParser - Alternative HTML::Parser interface
  140.  
  141. =head1 SYNOPSIS
  142.  
  143.  require HTML::TokeParser;
  144.  $p = HTML::TokeParser->new("index.html") || die "Can't open: $!";
  145.  while (my $token = $p->get_token) {
  146.      #...
  147.  }
  148.  
  149. =head1 DESCRIPTION
  150.  
  151. The HTML::TokeParser is an alternative interface to the HTML::Parser class.
  152. It basically turns the HTML::Parser inside out.  You associate a file
  153. (or any IO::Handle object or string) with the parser at construction time and
  154. then repeatedly call $parser->get_token to obtain the tags and text
  155. found in the parsed document.  No need to make a subclass to make the
  156. parser do anything.
  157.  
  158. Calling the methods defined by the HTML::Parser base class will be
  159. confusing, so don't do that.  Use the following methods instead:
  160.  
  161. =over 4
  162.  
  163. =item $p = HTML::TokeParser->new( $file_or_doc );
  164.  
  165. The object constructor argument is either a file name, a file handle
  166. object, or the complete document to be parsed.
  167.  
  168. If the argument is a plain scalar, then it is taken as the name of a
  169. file to be opened and parsed.  If the file can't be opened for
  170. reading, then the constructor will return an undefined value and $!
  171. will tell you why it failed.
  172.  
  173. If the argument is a reference to a plain scalar, then this scalar is
  174. taken to be the document to parse.
  175.  
  176. Otherwise the argument is taken to be some object that the
  177. C<HTML::TokeParser> can read() from when it need more data.  Typically
  178. it will be a filehandle of some kind.The stream will be read() until
  179. EOF, but not closed.
  180.  
  181. =item $p->get_token
  182.  
  183. This method will return the next I<token> found in the HTML document,
  184. or C<undef> at the end of the document.  The token is returned as an
  185. array reference.  The first element of the array will be a single
  186. character string denoting the type of this token; "S" for start tag,
  187. "E" for end tag, "T" for text, "C" for comment, and "D" for
  188. declaration.  The rest of the array is the same as the arguments
  189. passed to the corresponding HTML::Parser callbacks (see
  190. L<HTML::Parser>).  This summarize the tokens that can occur:
  191.  
  192.   ["S", $tag, %$attr, @$attrseq, $origtext]
  193.   ["E", $tag, $origtext]
  194.   ["T", $text]
  195.   ["C", $text]
  196.   ["D", $text]
  197.  
  198. =item $p->unget_token($token,...)
  199.  
  200. If you find out you have read too many tokens you can push them back,
  201. so that they are returned the next time $p->get_token is called.
  202.  
  203. =item $p->get_tag( [$tag] )
  204.  
  205. This method return the next start or end tag (skipping any other
  206. tokens), or C<undef> if there is no more tags in the document.  If an
  207. argument is given, then we skip tokens until the specified tag is
  208. found.  A tag is returned as an array reference of the same form as
  209. for $p->get_token above, but the type code (first element) is missing
  210. and the name of end tags are prefixed with "/".  This means that the
  211. tags returned look like this:
  212.  
  213.   [$tag, %$attr, @$attrseq, $origtext]
  214.   ["/$tag", $origtext]
  215.  
  216. =item $p->get_text( [$endtag] )
  217.  
  218. This method returns all text found at the current position. It will
  219. return a zero length string if the next token is not text.  The
  220. optional $endtag argument specify that any text occurring before the
  221. given tag is to be returned.  Any entities will be expanded to their
  222. corresponding character.
  223.  
  224. The $p->{textify} attribute is a hash that define how certain tags can
  225. be treated as text.  If the name of a start tag match a key in this
  226. hash then this tag is converted to text.  The hash value is used to
  227. specify which tag attribute to obtain the text from.  If this tag
  228. attribute is missing, then the upper case name of the tag enclosed in
  229. brackets is returned, e.g. "[IMG]".  The hash value can also be a
  230. subroutine reference.  In this case the routine is called with the
  231. start tag token content as arguments and the return values is treated
  232. as the text.
  233.  
  234. The default $p->{textify} value is:
  235.  
  236.   {img => "alt", applet => "alt"}
  237.  
  238. This means that <IMG> and <APPLET> tags are treated as text, and that
  239. the text to substitute can be found as ALT attribute.
  240.  
  241. =item $p->get_trimmed_text( [$endtag] )
  242.  
  243. Same as $p->get_text above, but will collapse any sequence of white
  244. space to a single space character.  Leading and trailing space is
  245. removed.
  246.  
  247. =back
  248.  
  249. =head1 EXAMPLES
  250.  
  251. This example extract all links from a document.  It will print one
  252. line for each link, containing the URL and the textual description
  253. between the <A>...</A> tags:
  254.  
  255.   use HTML::TokeParser;
  256.   $p = HTML::TokeParser->new(shift||"index.html");
  257.  
  258.   while (my $token = $p->get_tag("a")) {
  259.       my $url = $token->[1]{href} || "-";
  260.       my $text = $p->get_trimmed_text("/a");
  261.       print "$url\t$text\n";
  262.   }
  263.  
  264. This example extract the <TITLE> from the document:
  265.  
  266.   use HTML::TokeParser;
  267.   $p = HTML::TokeParser->new(shift||"index.html");
  268.   if ($p->get_tag("title")) {
  269.       my $title = $p->get_trimmed_text;
  270.       print "Title: $title\n";
  271.   }
  272.  
  273. =head1 SEE ALSO
  274.  
  275. L<HTML::Parser>
  276.  
  277. =head1 COPYRIGHT
  278.  
  279. Copyright 1998-1999 Gisle Aas.
  280.  
  281. This library is free software; you can redistribute it and/or
  282. modify it under the same terms as Perl itself.
  283.  
  284. =cut
  285.