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 is 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. This is an HTML::Parser
subclass that allows a more conventional program structure.
This class method creates a new HTML::Parser object and
returns it. Key/value argument pairs may be provided to assign event
handlers or initialize parser options. The handlers and parser
options can also be set or modified later by the 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.
The 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.
Parse $string as the next chunk of the HTML document. The return
value is normally a reference to the parser object (i.e. $p).
Handlers invoked should not attempt to modify the $string in-place until
$p->parse returns.
If an invoked event handler aborts parsing by calling $p->eof, then
$p->parse() will return a FALSE value.
$p->parse( $code_ref )
If a code reference is passed as the argument to be parsed, then the
chunks to be parsed are obtained by invoking this function repeatedly.
Parsing continues until the function returns an empty (or undefined)
result. When this happens $p->eof is automatically signaled.
Parsing will also abort if one of the event handlers calls $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.
Parse text directly from a file. The $file argument can be a
filename, an open file handle, or a reference to an open file
handle.
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 ifparse_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.
Signals the end of the HTML document. Calling the $p->eof method
outside a handler callback will flush any remaining buffered text
(which triggers the 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:
This method sets the value reported for boolean attributes inside HTML
start tags. By default, the name of the attribute is also used as its
value. This affects the values reported for tokens and attr
argspecs.
By default, ``plaintext'' element can never be closed. Everything up to
the end of the document is parsed in CDATA mode. This historical
behaviour is what at least MSIE does. Enabling this attribute makes
closing ``</plaintext>'' tag effective and the parsing process will resume
after seeing this tag. This emulates gecko-based browsers.
By default, empty element tags are not recognized as such and the ``/''
before ``>'' is just treated like a normal name character (unless
strict_names is enabled). Enabling this attribute make
HTML::Parser recognize these tags.
Empty element tags look like start tags, but end with the character
sequence ``/>'' instead of ``>''. 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 the token array will have one
element containing the tag name.
By default, comments are terminated by the first occurrence of ``-->''.
This is the behaviour of most popular browsers (like Mozilla, Opera and
MSIE), but it is not correct according to the official HTML
standard. Officially, you need an even number of ``--'' tokens before
the closing ``>'' is recognized and there may not be anything but
whitespace between an even and an odd ``--''.
The official behaviour is enabled by enabling this attribute.
Enabling of 'strict_comment' also disables recognizing these forms as
comments:
By default, almost anything is allowed in tag and attribute names.
This is the behaviour of most popular browsers and allows us to parse
some broken tags with invalid attribute values like:
By default, ``LIST]'' is parsed as a boolean attribute, not as
part of the ALT value as was clearly intended. This is also what
Mozilla 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.
By default, blocks of text are given to the text handler as soon as
possible (but the parser takes care always to break text at a
boundary between whitespace and non-whitespace so single words and
entities can always be decoded safely). This might create breaks that
make it hard to do transformations on the text. When this attribute is
enabled, blocks of text are always reported in one piece. This will
delay the text event until the following (non-text) event has been
recognized by the parser.
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.
Enable this option when parsing raw undecoded UTF-8. This tells the
parser that the entities expanded for strings reported by attr,
@attr and dtext should be expanded as decoded UTF-8 so they end
up compatible with the surrounding text.
If utf8_mode is enabled then it is an error to pass strings
containing characters with code above 255 to the parse() method, and
the parse() method will croak if you try.
Example: The Unicode character ``\x{2665}'' is ``\xE2\x99\xA5'' when UTF-8
encoded. The character can also be represented by the entity
``♥'' or ``♥''. If we feed the parser:
$p->parse("\xE2\x99\xA5♥");
then dtext will be reported as ``\xE2\x99\xA5\x{2665}'' without
utf8_mode enabled, but as ``\xE2\x99\xA5\xE2\x99\xA5'' when enabled.
The later string is what you want.
This option is only available with perl-5.8 or better.
Enabling this attribute changes the parser to allow some XML
constructs. This enables the behaviour controlled by individually by
the case_sensitive, empty_element_tags, strict_names and
xml_picattributes and also suppresses special treatment of
elements that are parsed as CDATA for HTML.
The \&subroutine is a reference to a subroutine which is called to handle
the event.
The $method_name is the name of a method of $p which is called to handle
the event.
The @accum is an 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.
The $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.
The return value from $p->handler 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.
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 suppresses
invocations 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 associated 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.
Both the start event and the end event as well as any events that
would be reported in between are suppressed. The ignored elements can
contain nested occurrences 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.
Any start and end events involving any of the tags given are
suppressed. To reset the filter (i.e. don't suppress any start and
end events), call ignore_tags without an argument.
Any start and end events involving any of the tags not given
are suppressed. To reset the filter (i.e. report all start and
end events), call report_tags without an argument.
Internally, the system has two filter lists, one for report_tags
and one for ignore_tags, and both filters are applied. This
effectively gives ignore_tags precedence over report_tags.
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:
Attr causes a reference to a hash of attribute name/value pairs to be
passed.
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.
Unless xml_mode or case_sensitive 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 is removed.
The Unicode character set is assumed for entity decoding. With Perl
version 5.6 or earlier only the Latin-1 range is supported, and
entities for characters outside the range 0..255 are left unchanged.
Basically the same as 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.
Dtext causes the decoded text to be passed. General entities are
automatically decoded unless the event was inside a CDATA section or
was between literal start and end tags (script, style,
xmp, and plaintext).
The Unicode character set is assumed for entity decoding. With Perl
version 5.6 or earlier only the Latin-1 range is supported, and
entities for characters outside the range 0..255 are left unchanged.
Is_cdata causes a TRUE value to be passed if the event is inside a CDATA
section or between literal start and end tags (script,
style, xmp, and plaintext).
if 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.
Line causes the line number of the start of the event to be passed.
The first line in the document is 1. Line counting doesn't start
until at least one handler requests this value to be reported.
Self causes the current object to be passed to the handler. If the
handler is a method, this must be the first element in the argspec.
An alternative to passing self as an argspec is to register closures
that capture $self by themselves as handlers. Unfortunately this
creates circular references which prevent the HTML::Parser object
from being garbage collected. Using the self argspec avoids this
problem.
Skipped_text returns the concatenated text of all the events that have
been skipped since the last time an event was reported. Events might
be skipped because no handler is registered for them or because some
filter applies. Skipped text also includes marked section markup,
since there are no events that can catch it.
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.
Same as 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.
This is the element name (or generic identifier in SGML jargon) for
start and end tags. Since HTML is case insensitive, this name is
forced to lower case to ease string matching.
Since XML is case sensitive, the tagname case is not changed when
xml_mode is enabled. The same happens if the case_sensitive attribute
is set.
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.
Tokenpos causes a reference to an array of token positions to be
passed. For each string that appears in 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 artificial 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.
Tokens causes a reference to an array of token strings to be passed.
The strings are exactly as they were found in the original text,
no decoding or case changes are applied.
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 values 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).
A literal string of 0 to 255 characters enclosed
in single (') or double (``) quotes is passed as entered.
The whole argspec string can be wrapped up in '@{...}' to signal
that the resulting event array should be flattened. This only makes a
difference if an array reference is used as the handler target.
Consider this example:
With two text events; "foo", "bar"; then the first example will end
up with [[``foo''], [``bar'']] and the second with [``foo'', ``bar''] in
the handler target array.
This event is triggered for events that do not have a specific
handler. You can set up a handler for this event to catch stuff you
did not want to catch explicitly.
This event is triggered before any other events for a new document. A
handler for it can be used to initialize stuff. There is no document
text associated with this event.
text
This event is triggered when plain text (characters) is recognized.
The text may contain multiple lines. A sequence of text may be broken
between several text events unless $p->unbroken_text is enabled.
The parser will make sure that it does not break a word or a sequence
of whitespace between two text events.
The HTML::Parser can parse Unicode strings when running under
perl-5.8 or better. If Unicode is passed to $p->parse() then chunks
of Unicode will be reported to the handlers. The offset and length
argspecs will also report their position in terms of characters.
It is safe to parse raw undecoded UTF-8 if you either avoid decoding
entities and make sure to not use argspecs that do, or enable the
utf8_mode for the parser. Parsing of undecoded UTF-8 might be
useful when parsing from a file where you need the reported offsets
and lengths to match the byte offsets in the file.
If a filename is passed to $p->parse_file() then the file will be read
in binary mode. This will be fine if the file contains only ASCII or
Latin-1 characters. If the file contains UTF-8 encoded text then care
must be taken when decoding entities as described in the previous
paragraph, but better is to open the file with the UTF-8 layer so that
it is decoded properly:
open(my $fh, "<:utf8", "index.html") || die "...: $!";
$p->parse_file($fh);
If the file contains text encoded in a charset besides ASCII, Latin-1
or UTF-8 then decoding will always be needed.
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.
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 single
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:
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; the program htextsub shows how to edit 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. The standard behaviour is
not really practical.
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
respectively.
NET tags, e.g. ``code/.../'' are not recognized. This is SGML
shorthand for ``<code>...</code>''.
Unclosed start or end tags, e.g. ``<tt<b>...</b</tt>'' are not
recognized.
(F) The _hparser_xs_state element does not refer to a valid state structure.
Something must have changed the internal value
stored in this hash element, or the memory has been overwritten.
(F) The first argument to $p->handler must be a valid event name; i.e. one
of ``start'', ``end'', ``text'', ``process'', ``declaration'' or ``comment''.
(W) The first chunk parsed appears to contain undecoded UTF-8 and one
or more argspecs that decode entities are used for the callback
handlers.
The result of decoding will be a mix of encoded and decoded characters
for any entities that expand to characters with code above 127. This
is not a good thing.
The solution is to use the Encode::encode_utf8() on the data before
feeding it to the $p->parse(). For $p->parse_file() pass a file that
has been opened in ``:utf8'' mode.
The parser can process raw undecoded UTF-8 sanely if the utf8_mode
is enabled or if the ``attr'', ``@attr'' or ``dtext'' argspecs is avoided.
(W) The first character in the document is U+FFFE. This is not a
legal Unicode character but a byte swapped BOM. The result of parsing
will likely be garbage.