man PSP::HTML::Parser () - HTML parser class


PSP::HTML::Parser - HTML parser class


This is the new XS based PSP::HTML::Parser. It should be completely backwards compatible with PSP::HTML::Parser version 2.2x, but has many new features and is significantly faster.


 use PSP::HTML::Parser ();

 # Create parser object
 $p = PSP::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->eof;                 # signal end of document

 # Parse directly from file
 # or
 open(F, "foo.html") || die;

PSP::HTML::Parser version 2 style subclassing and method callbacks:

    package MyParser;
    use base 'PSP::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;


Objects of the CWPSP::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.

CWPSP::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 CWPSP::HTML::TokeParser. It is a CWPSP::HTML::Parser subclass that allows a more conventional program structure.


The following method is used to construct a new CWPSP::HTML::Parser object: This class method creates a new CWPSP::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 CWPSP::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 = PSP::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 = PSP::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 CW$p and the tokens array.
 $p = PSP::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 CW@array for text and comment events.

The following methods feed the HTML document to the CWPSP::HTML::Parser object: Parse CW$string as the next chunk of the HTML document. The return value is normally a reference to the parser object (i.e. CW$p). Handlers invoked should not attempt modify the CW$string in-place until CW$p->parse returns. If an invoked event handler aborts parsing by calling CW$p->eof, then CW$p->parse() will return a FALSE value. Parse text directly from a file. The CW$file argument can be a filename, an open file handle, or a reference to a an open file handle. If CW$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 CW$file argument, then the file will normally be read until EOF, but not closed. If an invoked event handler aborts parsing by calling CW$p->eof, then CW$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 with a file handle that is not in binary mode.

Signals the end of the HTML document. Calling the CW$p->eof method outside a handler callback will flush any remaining buffered text (which triggers the CWtext event if there is any remaining text). Calling CW$p->eof inside a handler will terminate parsing at that point and cause CW$p->parse to return a FALSE value. This also terminates parsing by CW$p->parse_file(). The return value 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:

$p->strict_comment( [$bool] )
By default, comments are terminated by the first occurrence of -->. This is the behaviour of most popular browsers (like Netscape 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.
$p->strict_names( [$bool] )
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 attr values like:
   <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. 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 CWtokens and CWattr argspecs.
$p->xml_mode( [$bool] )
Enabling this attribute changes the parser to allow some XML constructs such as empty element tags and XML processing instructions. It disables forcing tag and attribute names to lower case when they are reported by the CWtagname and CWattr 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 CWPSP::HTML::Parser they cause an artificial end event in addition to the start event. The CWtext for the artificial end event will be empty and the CWtokenpos 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.
$p->unbroken_text( [$bool] )
By default, blocks of text are given to the text handler as soon as possible (but the parser makes sure to always break text at the boundary between whitespace and non-whitespace so single words and entities always can 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.
$p->marked_sections( [$bool] )
By default, section markings like <![CDATA[...]]> are treated like ordinary text. When this attribute is enabled section markings are honoured. There are currently no events associated with marked section elements.

As markup and text is recognized, handlers are invoked. The following method is used to set up handlers for different events:

$p->handler( event => \&subroutine, argspec )
$p->handler( event => method_name, argspec )
$p->handler( event => \@accum, argspec )
$p->handler( event => undef );
$p->handler( event );
This method assigns a subroutine, method, or array to handle an event. Event is one of CWtext, CWstart, CWend, CWdeclaration, CWcomment, CWprocess or CWdefault. Subroutine is a reference to a subroutine which is called to handle the event. Method_name is the name of a method of CW$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 CWundef. If argspec is omitted, then it is left unchanged since last update. The return value from CW$p->handle is the old callback routine or a reference to the accumulator array. Return values from handler callback routines/methods are always ignored. A handler callback can request parsing to be aborted by invoking the CW$p->eof method. A handler callback is not allowed to invoke CW$p->parse() or CW$p->parse_file(). Examples:
    $p->handler(start =>  "start", 'self, attr, attrseq, text' );
This causes the start method of object CW$p to be called for 'start' events. The callback signature is CW$p->start(\%attr, \@attr_seq, CW$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, CW$text).
    $p->handler(start =>  \@accum, '"S", attr, attrseq, text' );
This causes 'start' event information to be saved in CW@accum. The array elements will be ['S', \%attr, \@attr_seq, CW$text].
   $p->handler(start => "");
This causes 'start' events to be ignored. It also supresses invokations of any default handler for start events. It is equivalent to CW$p->handler(start => sub {}), but is more efficient.
   $p->handler(start => undef);
This causes no handler to be assosiated with start events. If there is a default handler it will be invoked.


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 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. 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 CWdeclaration events, the array contains each word, comment, and delimited string starting with the declaration type. For CWcomment events, this contains each sub-comment. If CW$p->strict_comments is disabled, there will be only one sub-comment. For CWstart 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 CW$p->boolean_attribute_value or the attribute name if no value has been set by CW$p->boolean_attribute_value. For CWend events, this contains the original tag name (one token only). For CWprocess events, this contains the process instructions (one token only). This passes CWundef for CWtext events. Tokenpos causes a reference to an array of token positions to be passed. For each string that appears in CWtokens, this array contains two numbers. The first number is the offset of the start of the token in the original CWtext and the second number is the length of the token. Boolean attributes in a CWstart 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., CWtext) and for artifical CWend events triggered by empty element tags. If you are using these offsets and lengths to modify CWtext, you should either work from right to left, or be very careful to calculate the changes to the offsets. Token0 causes the original text of the first token string to be passed. This should always be the same as CW$tokens->[0]. For CWdeclaration events, this is the declaration type. For CWstart and CWend events, this is the tag name. For CWprocess and non-strict CWcomment events, this is everything inside the tag. This passes undef if there are no tokens in the event. 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 CWxml_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 CWtoken0 except that the name may be forced to lower case. Attr causes a reference to a hash of attribute name/value pairs to be passed. Boolean attributes' values are either the value set by CW$p->boolean_attribute_value or the attribute name if no value has been set by CW$p->boolean_attribute_value. This passes undef except for CWstart events. Unless CWxml_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 causes a reference to an array of attribute names to be passed. This can be useful if you want to walk the CWattr hash in the original sequence. This passes undef except for CWstart events. Unless CWxml_mode is enabled, the attribute names are forced to lower case. Text causes the source text (including markup element delimiters) to be passed. 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 (CWscript, CWstyle, CWxmp, and CWplaintext). The ISO 8859-1 character set (aka Latin1) is assumed for entity decoding. It is planned that CWPSP::HTML::Parser will get an CWutf8 option at some point that will affect the byte sequence that characters with codes greater than 127 will decode into. This passes undef except for CWtext events. Is_cdata causes a TRUE value to be passed if the event is inside a CDATA section or is between literal start and end tags (CWscript, CWstyle, CWxmp, and CWplaintext). When the flag is FALSE for a text event, then you should normally either use CWdtext or decode the entities yourself before the text is processed further. Offset causes the byte position in the HTML document of the start of the event to be passed. The first byte in the document is 0. Length causes the number of bytes of the source text of the event to be passed. Event causes the event name to be passed. The event name is one of CWtext, CWstart, CWend, CWdeclaration, CWcomment, CWprocess or CWdefault. Note: This is not supported yet! 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. A literal string of 0 to 255 characters enclosed in single (') or double (") quotes is passed as entered. Pass an undefined value. Useful as padding.


Handlers for the following events can be registered: This event is triggered when plain text is recognized. The text may contain multiple lines. A sequence of text may be broken between several text events unless CW$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. This event is triggered when a start tag is recognized. Example:

  <A HREF="">
This event is triggered when an end tag is recognized. Example:
This event is triggered when a markup declaration is recognized. For typical HTML documents, the only declaration you are likely to find is <!DOCTYPE ...>. Example:
DTDs inside <!DOCTYPE ...> will confuse PSP::HTML::Parser. This event is triggered when a markup comment is recognized. Example:
  <!-- This is a comment -- -- So is this -->
This event is triggered when a processing instructions markup is recognized. The format and content of processing instructions is system and application dependent. Examples:
  <? HTML processing instructions >
  <? XML processing instructions ?>
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.


When an CWPSP::HTML::Parser object is constructed with no arguments, a set of handlers is automatically provided that is compatible with the old PSP::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 CWPSP::HTML::Parser class is subclassable. Parser objects are plain hashes and CWPSP::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 PSP::HTML::Parser;
  PSP::HTML::Parser->new(default_h => [sub { print shift }, 'text'],
                    comment_h => [""],
                   )->parse_file(shift || die) || die $!;

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 PSP::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"; },

  my $p = PSP::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 CWHTML-Parser distribution; the program CWhrefsub shows how you can edit all links found in a document and CWhtextsub how to edid the text only; the program CWhstrip shows how you can strip out certain tags/elements and/or attributes; and the program CWhtext show how to obtain the plain text, but not any script/style content.


CWPSP::HTML::Parser will leave <plaintext> mode when it sees </plaintext>. Plaintext mode should not really be escapeable.

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 CW$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 PSP::HTML::Parser. The notation in this listing is the same as used in perldiag:

Not a reference to a hash
(F) The object blessed into or subclassed from PSP::HTML::Parser is not a hash as required by the PSP::HTML::Parser methods. (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.
_hparser_xs_state element is not a reference
(F) The _hparser_xs_state element has been destroyed.
Can't find '_hparser_xs_state' element in PSP::HTML::Parser hash
(F) The _hparser_xs_state element is missing from the parser hash. It was either deleted, or not created when the object was created. (F) The constructor option 'api_version' with an argument greater than or equal to 4 is reserved for future extentions.
Bad constructor option '%s'
(F) An unknown constructor option key was passed to the new() or init() methods.
Parse loop not allowed
(F) A handler invoked the parse() or parse_file() method. This is not permitted.
marked sections not supported
(F) The CW$p->marked_sections() method was invoked in a PSP::HTML::Parser module that was compiled without support for marked sections.
Unknown boolean attribute (%d)
(F) Something is wrong with the internal logic that set up aliases for boolean attributes.
Only code or array references allowed as handler
(F) The second argument for CW$p->handler must be either a subroutine reference, then name of a subroutine or method, or a reference to an array. (F) The first argument to CW$p->handler must be a valid event name; i.e. one of start, end, text, process, declaration or comment. (F) The identifier is not a known argspec name. Use one of the names mentioned in the argspec section above.
Literal string is longer than 255 chars in argspec
(F) The current implementation limits the length of literals in an argspec to 255 characters. Make the literal shorter.
Backslash reserved for literal string in argspec
(F) The backslash character \ is not allowed in argspec literals. It is reserved to permit quoting inside a literal in a later version.
Unterminated literal string in argspec
(F) The terminating quote character for a literal was not found.
Bad argspec (%s)
(F) Only identifier names, literals, spaces and commas are allowed in argspecs.
Missing comma separator in argspec
(F) Identifiers in an argspec must be separated with ,.


PSP::HTML::Entities, PSP::HTML::TokeParser, PSP::HTML::HeadParser, PSP::HTML::LinkExtor, PSP::HTML::Form

HTML::TreeBuilder (part of the HTML-Tree distribution)

More information about marked sections and processing instructions may be found at CW


 Copyright 1996-2000 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.