HTML::Parser - HTML parser class |
HTML::Parser - HTML parser class
use HTML::Parser ();
# Create parser object $p = HTML::Parser->new( api_version => 3, start_h => [\&start, "tagname, attr"], end_h => [\&end, "tagname"], marked_sections => 1, );
# Parse document text chunk by chunk $p->parse($chunk1); $p->parse($chunk2); #... $p->eof; # signal end of document
# Parse directly from file $p->parse_file("foo.html"); # or open(F, "foo.html") || die; $p->parse_file(*F);
HTML::Parser version 2 style subclassing and method callbacks:
{ package MyParser; use base 'HTML::Parser';
sub start { my($self, $tagname, $attr, $attrseq, $origtext) = @_; #... }
sub end { my($self, $tagname, $origtext) = @_; #... }
sub text { my($self, $origtext, $is_cdata) = @_; #... } }
my $p = MyParser->new; $p->parse_file("foo.html");
Objects of the HTML::Parser
class will recognize markup and
separate it from plain text (alias data content) in HTML
documents. As different kinds of markup and text are recognized, the
corresponding event handlers are invoked.
HTML::Parser
in not a generic SGML parser. We have tried to
make it able to deal with the HTML that is actually ``out there'', and
it normally parses as closely as possible to the way the popular web
browsers do it instead of strictly following one of the many HTML
specifications from W3C. Where there is disagreement there is often
an option that you can enable to get the official behaviour.
The document to be parsed may be supplied in arbitrary chunks. This makes on-the-fly parsing as documents are received from the network possible.
If event driven parsing does not feel right for your application, you
might want to use HTML::PullParser
. It is a
HTML::Parser
subclass that allows a more conventional program
structure.
The following method is used to construct a new HTML::Parser
object:
HTML::Parser
object and
returns it. Key/value pair arguments may be provided to assign event
handlers or initialize parser options. The handlers and parser
options can also be set or modified later by method calls described below.
If a top level key is in the form ``<event>_h'' (e.g., ``text_h''} then it assigns a handler to that event, otherwise it initializes a parser option. The event handler specification value must be an array reference. Multiple handlers may also be assigned with the 'handlers => [%handlers]' option. See examples below.
If new()
is called without any arguments, it will create a parser that
uses callback methods compatible with version 2 of HTML::Parser
.
See the section on ``version 2 compatibility'' below for details.
Special constructor option 'api_version => 2' can be used to initialize version 2 callbacks while still setting other options and handlers. The 'api_version => 3' option can be used if you don't want to set any options and don't want to fall back to v2 compatible mode.
Examples:
$p = HTML::Parser->new(api_version => 3, text_h => [ sub {...}, "dtext" ]);
This creates a new parser object with a text event handler subroutine that receives the original text with general entities decoded.
$p = HTML::Parser->new(api_version => 3, start_h => [ 'my_start', "self,tokens" ]);
This creates a new parser object with a start event handler method that receives the $p and the tokens array.
$p = HTML::Parser->new(api_version => 3, handlers => { text => [\@array, "event,text"], comment => [\@array, "event,text"], });
This creates a new parser object that stores the event type and the original text in @array for text and comment events.
The following methods feed the HTML document
to the HTML::Parser
object:
If an invoked event handler aborts parsing by calling $p->eof, then
$p->parse()
will return a FALSE value.
Parsing will also abort if one of the event handlers call $p->eof.
The effect of this is the same as:
while (1) { my $chunk = &$code_ref(); if (!defined($chunk) || !length($chunk)) { $p->eof; return $p; } $p->parse($chunk) || return undef; }
But it is more efficient as this loop runs internally in XS code.
If $file contains a filename and the file can't be opened, then the method returns an undefined value and $! tells why it failed. Otherwise the return value is a reference to the parser object.
If a file handle is passed as the $file argument, then the file will normally be read until EOF, but not closed.
If an invoked event handler aborts parsing by calling $p->eof,
then $p->parse_file()
may not have read the entire file.
On systems with multi-byte line terminators, the values passed for the
offset and length argspecs may be too low if parse_file()
is called on
a file handle that is not in binary mode.
If a filename is passed in, then parse_file()
will open the file in
binary mode.
text
event if there is any remaining text).
Calling $p->eof inside a handler will terminate parsing at that point and cause $p->parse to return a FALSE value. This also terminates parsing by $p->parse_file().
After $p->eof has been called, the parse()
and parse_file()
methods
can be invoked to feed new documents with the parser object.
The return value from eof()
is a reference to the parser object.
Most parser options are controlled by boolean attributes. Each boolean attribute is enabled by calling the corresponding method with a TRUE argument and disabled with a FALSE argument. The attribute value is left unchanged if no argument is given. The return value from each method is the old attribute value.
Methods that can be used to get and/or set parser options are:
The official behaviour is enabled by enabling this attribute.
<IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0>
By default, ``LIST]'' is parsed as a boolean attribute, not as part of the ALT value as was clearly intended. This is also what Netscape sees.
The official behaviour is enabled by enabling this attribute. If enabled, it will cause the tag above to be reported as text since ``LIST]'' is not a legal attribute name.
tokens
and attr
argspecs.
tagname
and attr
argspecs,
and suppress special treatment of elements that are parsed as CDATA
for HTML.
Empty element tags look like start tags, but end with the character
sequence ``/>''. When recognized by HTML::Parser
they cause an
artificial end event in addition to the start event. The text
for
the artificial end event will be empty and the tokenpos
array will
be undefined even though the only element in the token array will have
the correct tag name.
XML processing instructions are terminated by ``?>'' instead of a simple ``>'' as is the case for HTML.
Note that the offset
argspec will give you the offset of the first
segment of text and length
is the combined length of the segments.
Since there might be ignored tags in between, these numbers can't be
used to directly index in the original document file.
There are currently no events associated with the marked section
markup, but the text can be returned as skipped_text
.
As markup and text is recognized, handlers are invoked. The following method is used to set up handlers for different events:
Event is one of text
, start
, end
, declaration
, comment
,
process
, start_document
, end_document
or default
.
Subroutine is a reference to a subroutine which is called to handle the event.
Method_name is the name of a method of $p which is called to handle the event.
Accum is a array that will hold the event information as sub-arrays.
If the second argument is ``'', the event is ignored. If it is undef, the default handler is invoked for the event.
Argspec is a string that describes the information to be reported
for the event. Any requested information that does not apply to a
specific event is passed as undef
. If argspec is omitted, then it
is left unchanged since last update.
The return value from $p->handle is the old callback routine or a reference to the accumulator array.
Any return values from handler callback routines/methods are always
ignored. A handler callback can request parsing to be aborted by
invoking the $p->eof method. A handler callback is not allowed to
invoke the $p->parse()
or $p->parse_file()
method. An exception will
be raised if it tries.
Examples:
$p->handler(start => "start", 'self, attr, attrseq, text' );
This causes the ``start'' method of object $p to be called for 'start' events. The callback signature is $p->start(\%attr, \@attr_seq, $text).
$p->handler(start => \&start, 'attr, attrseq, text' );
This causes subroutine start()
to be called for 'start' events.
The callback signature is start(\%attr, \@attr_seq, $text).
$p->handler(start => \@accum, '"S", attr, attrseq, text' );
This causes 'start' event information to be saved in @accum. The array elements will be ['S', \%attr, \@attr_seq, $text].
$p->handler(start => "");
This causes 'start' events to be ignored. It also supresses
invokations of any default handler for start events. It is in most
cases equivalent to $p->handler(start => sub {}), but is more
efficient. It is different from the empty-sub-handler in that
skipped_text
is not reset by it.
$p->handler(start => undef);
This causes no handler to be assosiated with start events. If there is a default handler it will be invoked.
Filters based on tags can be set up to limit the number of events reported. The main bottleneck during parsing is often the huge number of callbacks made from the parser. Applying filters can improve performance significantly.
The following methods control filters:
start
and end
events involving any of the tags given are
suppressed.
start
and end
events involving any of the tags not given
are suppressed.
start
and the end
event as well as any events that
would be reported in between are suppressed. The ignored elements can
contain nested occurences of itself. Example:
$p->ignore_elements(qw(script style));
The script
and style
tags will always nest properly since their
content is parsed in CDATA mode. For most other tags
ignore_elements
must be used with caution since HTML is often not
well formed.
Argspec is a string containing a comma separated list that describes the information reported by the event. The following argspec identifier names can be used:
self
An alternative to passing self as an argspec is to register closures
that capture $self by themselves as handlers. Unfortunately this
creates a circular references which prevents the HTML::Parser object
from being garbage collected. Using the self
argspec avoids this
problem.
tokens
For declaration
events, the array contains each word, comment, and
delimited string starting with the declaration type.
For comment
events, this contains each sub-comment. If
$p->strict_comments is disabled, there will be only one sub-comment.
For start
events, this contains the original tag name followed by
the attribute name/value pairs. The value of boolean attributes will
be either the value set by $p->boolean_attribute_value or the
attribute name if no value has been set by
$p->boolean_attribute_value.
For end
events, this contains the original tag name (always one token).
For process
events, this contains the process instructions (always one
token).
tokenpos
tokens
, this array
contains two numbers. The first number is the offset of the start of
the token in the original text
and the second number is the length
of the token.
Boolean attributes in a start
event will have (0,0) for the
attribute value offset and length.
This passes undef if there are no tokens in the event (e.g., text
)
and for artifical end
events triggered by empty element tags.
If you are using these offsets and lengths to modify text
, you
should either work from right to left, or be very careful to calculate
the changes to the offsets.
token0
For declaration
events, this is the declaration type.
For start
and end
events, this is the tag name.
For process
and non-strict comment
events, this is everything
inside the tag.
This passes undef if there are no tokens in the event.
tagname
Since XML is case sensitive, the tagname case is not
changed when xml_mode
is enabled.
The declaration type of declaration elements is also passed as a tagname,
even if that is a bit strange.
In fact, in the current implementation tagname is
identical to token0
except that the name may be forced to lower case.
tag
tagname
, but prefixed with ``/'' if it belongs to an end
event and ``!'' for a declaration. The tag
does not have any prefix
for start
events, and is in this case identical to tagname
.
attr
Boolean attributes' values are either the value set by $p->boolean_attribute_value or the attribute name if no value has been set by $p->boolean_attribute_value.
This passes undef except for start
events.
Unless xml_mode
is enabled, the attribute names are forced to
lower case.
General entities are decoded in the attribute values and one layer of matching quotes enclosing the attribute values are removed.
attrseq
attr
hash in
the original sequence.
This passes undef except for start
events.
Unless xml_mode
is enabled, the attribute names are forced to lower
case.
@attr
attr
, but keys and values are passed as
individual arguments and the original sequence of the attributes is
kept. The parameters passed will be the same as the @attr calculated
here:
@attr = map { $_ => $attr->{$_} } @$attrseq;
assuming $attr and $attrseq here are the hash and array passed as the
result of attr
and attrseq
argspecs.
This pass no values for events besides start
.
text
dtext
script
, style
, xmp
,
and plaintext
).
The Unicode character set is assumed for entity decoding. With perl version < 5.7.1 only the Latin1 range is supported, and entities for characters outside the 0..255 range is left unchanged.
This passes undef except for text
events.
is_cdata
script
,
style
, xmp
, and plaintext
).
When the flag is FALSE for a text event, then you should normally
either use dtext
or decode the entities yourself before the text is
processed further.
skipped_text
If an ""
-handler is registered for an event, then the text for this
event is not included in skipped_text
. Skipped text both before
and after the ""
-event is included in the next reported
skipped_text
.
offset
length
offset_end
offset
+ length
.
event
The event name is one of text
, start
, end
, declaration
,
comment
, process
, start_document
, end_document
or default
.
line
column
'...'
undef
The whole argspec string can be wrapped up in '@{...}'
to signal
that resulting event array should be flatten. This only makes a
difference if an array reference is used as the handler target.
Consider this example:
$p->handler(text => [], 'text'); $p->handler(text => [], '@{text}']);
With two text events; "foo"
, "bar"
; then the first one will end
up with [[``foo''], [``bar'']] and the second one with [``foo'', ``bar''] in
the handler target array.
Handlers for the following events can be registered:
text
The parser will make sure that it does not break a word or a sequence of whitespace between two text events.
start
Example:
<A HREF="http://www.perl.com/">
end
Example:
</A>
declaration
For typical HTML documents, the only declaration you are likely to find is <!DOCTYPE ...>.
Example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html40/strict.dtd">
DTDs inside <!DOCTYPE ...> will confuse HTML::Parser.
comment
Example:
<!-- This is a comment -- -- So is this -->
process
The format and content of processing instructions is system and application dependent.
Examples:
<? HTML processing instructions > <? XML processing instructions ?>
start_document
end_document
default
When an HTML::Parser
object is constructed with no arguments, a set
of handlers is automatically provided that is compatible with the old
HTML::Parser version 2 callback methods.
This is equivalent to the following method calls:
$p->handler(start => "start", "self, tagname, attr, attrseq, text"); $p->handler(end => "end", "self, tagname, text"); $p->handler(text => "text", "self, text, is_cdata"); $p->handler(process => "process", "self, token0, text"); $p->handler(comment => sub { my($self, $tokens) = @_; for (@$tokens) {$self->comment($_);}}, "self, tokens"); $p->handler(declaration => sub { my $self = shift; $self->declaration(substr($_[0], 2, -1));}, "self, text");
Setup of these handlers can also be requested with the ``api_version => 2'' constructor option.
The HTML::Parser
class is subclassable. Parser objects are plain
hashes and HTML::Parser
reserves only hash keys that start with
``_hparser''. The parser state can be set up by invoking the init()
method which takes the same arguments as new().
The first simple example shows how you might strip out comments from an HTML document. We achieve this by setting up a comment handler that does nothing and a default handler that will print out anything else:
use HTML::Parser; HTML::Parser->new(default_h => [sub { print shift }, 'text'], comment_h => [""], )->parse_file(shift || die) || die $!;
An alternative implementation is:
use HTML::Parser; HTML::Parser->new(end_document_h => [sub { print shift }, 'skipped_text'], comment_h => [""], )->parse_file(shift || die) || die $!;
This will in most cases be much more efficient since only a sigle callback will be made.
The next example prints out the text that is inside the <title> element of an HTML document. Here we start by setting up a start handler. When it sees the title start tag it enables a text handler that prints any text found and an end handler that will terminate parsing as soon as the title end tag is seen:
use HTML::Parser ();
sub start_handler { return if shift ne "title"; my $self = shift; $self->handler(text => sub { print shift }, "dtext"); $self->handler(end => sub { shift->eof if shift eq "title"; }, "tagname,self"); }
my $p = HTML::Parser->new(api_version => 3); $p->handler( start => \&start_handler, "tagname,self"); $p->parse_file(shift || die) || die $!; print "\n";
More examples are found in the ``eg/'' directory of the HTML-Parser
distribution; the program hrefsub
shows how you can edit all links
found in a document and htextsub
how to edid the text only; the
program hstrip
shows how you can strip out certain tags/elements
and/or attributes; and the program htext
show how to obtain the
plain text, but not any script/style content.
The <style> and <script> sections do not end with the first ``</'', but need the complete corresponding end tag.
When the strict_comment option is enabled, we still recognize comments where there is something other than whitespace between even and odd ``--'' markers.
Once $p->boolean_attribute_value has been set, there is no way to restore the default behaviour.
There is currently no way to get both quote characters into the same literal argspec.
Empty tags, e.g. ``<>'' and ``</>'', are not recognized. SGML allows them to repeat the previous start tag or close the previous start tag respecitvely.
NET tags, e.g. ``code/.../'' are not recognized. This is an SGML shorthand for ``<code>...</code>''.
Unclosed start or end tags, e.g. ``<tt<b>...</b</tt>'' are not recognized.
The following messages may be produced by HTML::Parser. The notation in this listing is the same as used in the perldiag manpage:
new()
or
init()
methods.
parse()
or parse_file()
method.
This is not permitted.
marked_sections()
method was invoked in a HTML::Parser
module that was compiled without support for marked sections.
the HTML::Entities manpage, the HTML::PullParser manpage, the HTML::TokeParser manpage, the HTML::HeadParser manpage, the HTML::LinkExtor manpage, the HTML::Form manpage
the HTML::TreeBuilder manpage (part of the HTML-Tree distribution)
http://www.w3.org/TR/REC-html40
More information about marked sections and processing instructions may
be found at http://www.sgml.u-net.com/book/sgml-8.htm
.
Copyright 1996-2001 Gisle Aas. All rights reserved. Copyright 1999-2000 Michael A. Chase. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
HTML::Parser - HTML parser class |