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

  1. package HTML::Parser;
  2.  
  3. # $Id: Parser.pm,v 2.12 1997/12/11 23:59:39 aas Exp $
  4.  
  5. use strict;
  6. use HTML::Entities ();
  7.  
  8. use vars qw($VERSION);
  9. $VERSION = sprintf("%d.%02d", q$Revision: 2.12 $ =~ /(\d+)\.(\d+)/);
  10.  
  11.  
  12. sub new
  13. {
  14.     my $class = shift;
  15.     my $self = bless { '_buf'            => '',
  16.                '_strict_comment' => 0,
  17.              }, $class;
  18.     $self;
  19. }
  20.  
  21.  
  22. # A note about how Netscape does it:
  23. #
  24. # It parse <xmp> in the depreceated 'literal' mode, i.e. no tags are
  25. # recognized until a </xmp> is found.
  26. # <listing> is parsed like <pre>, i.e. tags are recognized.  <listing>
  27. # are presentend in smaller font than <pre>
  28. #
  29. # Netscape does not parse this comment correctly (it terminates the comment
  30. # too early):
  31. #
  32. #    <! -- comment -- --> more comment -->
  33. #
  34. # Netscape does not allow space after the initial "<" in the start tag.
  35. # Like this "<a href='gisle'>"
  36. #
  37. # Netscape ignores '<!--' and '-->' within the <SCRIPT> and <STYLE> tag.
  38. # This is used as a trick to make non-script-aware browsers ignore
  39. # the scripts.
  40.  
  41.  
  42. sub parse
  43. {
  44.     my $self = shift;
  45.     my $buf = \ $self->{'_buf'};
  46.     unless (defined $_[0]) {
  47.     # signals EOF (assume rest is plain text)
  48.     $self->text($$buf) if length $$buf;
  49.     $$buf = '';
  50.     return $self;
  51.     }
  52.     $$buf .= $_[0];
  53.     my $netscape_comment = !$self->{'_strict_comment'};
  54.  
  55.     # Parse html text in $$buf.  The strategy is to remove complete
  56.     # tokens from the beginning of $$buf until we can't deside whether
  57.     # it is a token or not, or the $$buf is empty.
  58.  
  59.   TOKEN:
  60.     while (1) {
  61.  
  62.     # First we try to pull off any plain text (anything before a "<" char)
  63.     if ($$buf =~ s|^([^<]+)||) {
  64.         unless (length $$buf) {
  65.         my $text = $1;
  66.         # At the end of the buffer, we should not parse white space
  67.         # but leave it for parsing on the next round.
  68.         if ($text =~ s|(\s+)$||) {
  69.             $$buf = $1;
  70.                 # Same treatment for chopped up entites.
  71.         } elsif ($text =~ s/(&(?:(?:\#\d*)?|\w*))$//) {
  72.             $$buf = $1;
  73.         };
  74.         $self->text($text);
  75.         last TOKEN;
  76.         } else {
  77.         $self->text($1);
  78.         }
  79.  
  80.     # Netscapes buggy comments are easy to handle
  81.     } elsif ($netscape_comment && $$buf =~ m|^<!--|) {
  82.         if ($$buf =~ s|^<!--(.*?)-->||s) {
  83.         $self->comment($1);
  84.         } else {
  85.         last TOKEN;  # must wait until we see the end of it
  86.         }
  87.  
  88.     # Then, markup declarations (usually either <!DOCTYPE...> or a comment)
  89.     } elsif ($$buf =~ s|^(<!)||) {
  90.         my $eaten = $1;
  91.         my $text = '';
  92.         my @com = ();  # keeps comments until we have seen the end
  93.         # Eat text and beginning of comment
  94.         while ($$buf =~ s|^(([^>]*?)--)||) {
  95.         $eaten .= $1;
  96.         $text .= $2;
  97.         # Look for end of comment
  98.         if ($$buf =~ s|^((.*?)--)||s) {
  99.             $eaten .= $1;
  100.             push(@com, $2);
  101.         } else {
  102.             # Need more data to get all comment text.
  103.             $$buf = $eaten . $$buf;
  104.             last TOKEN;
  105.         }
  106.         }
  107.         # Can we finish the tag
  108.         if ($$buf =~ s|^([^>]*)>||) {
  109.         $text .= $1;
  110.         $self->declaration($text) if $text =~ /\S/;
  111.         # then tell about all the comments we found
  112.         for (@com) { $self->comment($_); }
  113.         } else {
  114.         $$buf = $eaten . $$buf;  # must start with it all next time
  115.         last TOKEN;
  116.         }
  117.  
  118.         # Should we look for 'processing instructions' <? ...> ??
  119.     #} elsif ($$buf =~ s|<\?||) {
  120.         # ...
  121.  
  122.     # Then, look for a end tag
  123.     } elsif ($$buf =~ s|^</||) {
  124.         # end tag
  125.         if ($$buf =~ s|^([a-zA-Z][a-zA-Z0-9\.\-]*)(\s*>)||) {
  126.         $self->end(lc($1), "</$1$2");
  127.         } elsif ($$buf =~ m|^[a-zA-Z]*[a-zA-Z0-9\.\-]*\s*$|) {
  128.         $$buf = "</" . $$buf;  # need more data to be sure
  129.         last TOKEN;
  130.         } else {
  131.         # it is plain text after all
  132.         $self->text("</");
  133.         }
  134.  
  135.     # Then, finally we look for a start tag
  136.     } elsif ($$buf =~ s|^(<([a-zA-Z]+)>)||) {
  137.         # special case plain start tags for slight speed-up (2.5%)
  138.         $self->start(lc($2), {}, [], $1);
  139.  
  140.     } elsif ($$buf =~ s|^<||) {
  141.         # start tag
  142.         my $eaten = '<';
  143.  
  144.         # This first thing we must find is a tag name.  RFC1866 says:
  145.         #   A name consists of a letter followed by letters,
  146.         #   digits, periods, or hyphens. The length of a name is
  147.         #   limited to 72 characters by the `NAMELEN' parameter in
  148.         #   the SGML declaration for HTML, 9.5, "SGML Declaration
  149.         #   for HTML".  In a start-tag, the element name must
  150.         #   immediately follow the tag open delimiter `<'.
  151.         if ($$buf =~ s|^(([a-zA-Z][a-zA-Z0-9\.\-]*)\s*)||) {
  152.         $eaten .= $1;
  153.         my $tag = lc $2;
  154.         my %attr;
  155.         my @attrseq;
  156.  
  157.         # Then we would like to find some attributes
  158.                 #
  159.                 # Arrgh!! Since stupid Netscape violates RCF1866 by
  160.                 # using "_" in attribute names (like "ADD_DATE") of
  161.                 # their bookmarks.html, we allow this too.
  162.         while ($$buf =~ s|^(([a-zA-Z][a-zA-Z0-9\.\-_]*)\s*)||) {
  163.             $eaten .= $1;
  164.             my $attr = lc $2;
  165.             my $val;
  166.             # The attribute might take an optional value (first we
  167.             # check for an unquoted value)
  168.             if ($$buf =~ s|(^=\s*([^\"\'>\s][^>\s]*)\s*)||) {
  169.             $eaten .= $1;
  170.             $val = $2;
  171.             HTML::Entities::decode($val);
  172.             # or quoted by " or '
  173.             } elsif ($$buf =~ s|(^=\s*([\"\'])(.*?)\2\s*)||s) {
  174.             $eaten .= $1;
  175.             $val = $3;
  176.             HTML::Entities::decode($val);
  177.                     # truncated just after the '=' or inside the attribute
  178.             } elsif ($$buf =~ m|^(=\s*)$| or
  179.                  $$buf =~ m|^(=\s*[\"\'].*)|s) {
  180.             $$buf = "$eaten$1";
  181.             last TOKEN;
  182.             } else {
  183.             # assume attribute with implicit value
  184.             $val = $attr;
  185.             }
  186.             $attr{$attr} = $val;
  187.             push(@attrseq, $attr);
  188.         }
  189.  
  190.         # At the end there should be a closing ">"
  191.         if ($$buf =~ s|^>||) {
  192.             $self->start($tag, \%attr, \@attrseq, "$eaten>");
  193.         } elsif (length $$buf) {
  194.             # Not a conforming start tag, regard it as normal text
  195.             $self->text($eaten);
  196.         } else {
  197.             $$buf = $eaten;  # need more data to know
  198.             last TOKEN;
  199.         }
  200.  
  201.         } elsif (length $$buf) {
  202.         $self->text($eaten);
  203.         } else {
  204.         $$buf = $eaten . $$buf;  # need more data to parse
  205.         last TOKEN;
  206.         }
  207.  
  208.     } else {
  209.         #die if length($$buf);  # This should never happen
  210.         last TOKEN;         # The buffer should be empty now
  211.     }
  212.     }
  213.  
  214.     $self;
  215. }
  216.  
  217.  
  218. sub eof
  219. {
  220.     shift->parse(undef);
  221. }
  222.  
  223.  
  224. sub parse_file
  225. {
  226.     my($self, $file) = @_;
  227.     no strict 'refs';  # so that a symbol ref as $file works
  228.     local(*F);
  229.     unless (ref($file) || $file =~ /^\*[\w:]+$/) {
  230.     # Assume $file is a filename
  231.     open(F, $file) || die "Can't open $file: $!";
  232.     $file = \*F;
  233.     }
  234.     my $chunk = '';
  235.     while(read($file, $chunk, 1024)) {
  236.     $self->parse($chunk);
  237.     }
  238.     close($file);
  239.     $self->eof;
  240. }
  241.  
  242.  
  243. sub strict_comment
  244. {
  245.     my $self = shift;
  246.     my $old = $self->{'_strict_comment'};
  247.     $self->{'_strict_comment'} = shift if @_;
  248.     return $old;
  249. }
  250.  
  251.  
  252. sub netscape_buggy_comment  # legacy
  253. {
  254.     my $self = shift;
  255.     my $old = !$self->strict_comment;
  256.     $self->strict_comment(!shift) if @_;
  257.     return $old;
  258. }
  259.  
  260.  
  261. sub text
  262. {
  263.     # my($self, $text) = @_;
  264. }
  265.  
  266. sub declaration
  267. {
  268.     # my($self, $decl) = @_;
  269. }
  270.  
  271. sub comment
  272. {
  273.     # my($self, $comment) = @_;
  274. }
  275.  
  276. sub start
  277. {
  278.     # my($self, $tag, $attr, $attrseq, $origtext) = @_;
  279.     # $attr is reference to a HASH, $attrseq is reference to an ARRAY
  280. }
  281.  
  282. sub end
  283. {
  284.     # my($self, $tag, $origtext) = @_;
  285. }
  286.  
  287. 1;
  288.  
  289.  
  290. __END__
  291.  
  292.  
  293. =head1 NAME
  294.  
  295. HTML::Parser - SGML parser class
  296.  
  297. =head1 SYNOPSIS
  298.  
  299.  require HTML::Parser;
  300.  $p = HTML::Parser->new;  # should really a be subclass
  301.  $p->parse($chunk1);
  302.  $p->parse($chunk2);
  303.  #...
  304.  $p->eof;                 # signal end of document
  305.  
  306.  # Parse directly from file
  307.  $p->parse_file("foo.html");
  308.  # or
  309.  open(F, "foo.html") || die;
  310.  $p->parse_file(\*F);
  311.  
  312. =head1 DESCRIPTION
  313.  
  314. The C<HTML::Parser> will tokenize an HTML document when the parse()
  315. method is called and invoke various callback methods.  The document to
  316. be parsed can be supplied in arbitrary chunks.
  317.  
  318. The external interface the an HTML::Parser is:
  319.  
  320. =over 4
  321.  
  322. =item $p = HTML::Parser->new
  323.  
  324. The object constructor takes no arguments.
  325.  
  326. =item $p->parse( $string );
  327.  
  328. Parse the $string as an HTML document.  Can be called multiple times.
  329. The return value is a reference to the parser object.
  330.  
  331. =item $p->eof
  332.  
  333. Signals end of document.  Call eof() to flush any remaining buffered
  334. text.  The return value is a reference to the parser object.
  335.  
  336. =item $p->parse_file( $file );
  337.  
  338. This method can be called to parse text from a file.  The argument can
  339. be a filename or an already opened file handle. The return value from
  340. parse_file() is a reference to the parser object.
  341.  
  342. =item $p->strict_comment( [$bool] )
  343.  
  344. By default we parse comments similar to how the popular browsers (like
  345. Netscape and MSIE) do it.  This means that comments will always be
  346. terminated by the first occurence of "-->".  This is not correct
  347. according to the "official" HTML standards.  The official behaviour
  348. can be enabled by calling the strict_comment() method with a TRUE
  349. argument.
  350.  
  351. The return value from strict_comment() is the old attribute value.
  352.  
  353. =back
  354.  
  355.  
  356.  
  357. In order to make the parser do anything interesting, you must make a
  358. subclass where you override one or more of the following methods as
  359. appropriate:
  360.  
  361. =over 4
  362.  
  363. =item $self->declaration($decl)
  364.  
  365. This method is called when a I<markup declaration> has been
  366. recognized.  For typical HTML documents, the only declaration you are
  367. likely to find is <!DOCTYPE ...>.  The initial "<!" and ending ">" is
  368. not part of the string passed as argument.  Comments are removed and
  369. entities will B<not> be expanded.
  370.  
  371. =item $self->start($tag, $attr, $attrseq, $origtext)
  372.  
  373. This method is called when a complete start tag has been recognized.
  374. The first argument is the tag name (in lower case) and the second
  375. argument is a reference to a hash that contain all attributes found
  376. within the start tag.  The attribute keys are converted to lower case.
  377. Entities found in the attribute values are already expanded.  The
  378. third argument is a reference to an array with the lower case
  379. attribute keys in the original order.  The fourth argument is the
  380. original HTML text.
  381.  
  382.  
  383. =item $self->end($tag, $origtext)
  384.  
  385. This method is called when an end tag has been recognized.  The
  386. first argument is the lower case tag name, the second the original
  387. HTML text of the tag.
  388.  
  389. =item $self->text($text)
  390.  
  391. This method is called when plain text in the document is recognized.
  392. The text is passed on unmodified and might contain multiple lines.
  393. Note that for efficiency reasons entities in the text are B<not>
  394. expanded.  You should call HTML::Entities::decode($text) before you
  395. process the text any further.
  396.  
  397. =item $self->comment($comment)
  398.  
  399. This method is called as comments are recognized.  The leading and
  400. trailing "--" sequences have been stripped off the comment text.
  401.  
  402. =back
  403.  
  404. The default implementation of these methods do nothing, i.e., the
  405. tokens are just ignored.
  406.  
  407. There is really nothing in the basic parser that is HTML specific, so
  408. it is likely that the parser can parse other kinds of SGML documents.
  409. SGML has many obscure features (not implemented by this module) that
  410. prevent us from renaming this module as C<SGML::Parser>.
  411.  
  412. =head1 EFFICIENCY
  413.  
  414. The parser is fairly inefficient if the chunks passed to $p->parse()
  415. are too big.  The reason is probably that perl ends up with a lot of
  416. character copying when tokens are removed from the beginning of the
  417. strings.  A chunck size of about 256-512 bytes was optimal in a test I
  418. made with some real world HTML documents.  (The parser was about 3
  419. times slower with a chunck size of 20K).
  420.  
  421. =head1 SEE ALSO
  422.  
  423. L<HTML::TreeBuilder>, L<HTML::HeadParser>, L<HTML::Entities>
  424.  
  425. =head1 COPYRIGHT
  426.  
  427. Copyright 1996-1997 Gisle Aas. All rights reserved.
  428.  
  429. This library is free software; you can redistribute it and/or
  430. modify it under the same terms as Perl itself.
  431.  
  432. =cut
  433.