1NAME
2 HTML::Parser - HTML parser class
3
4SYNOPSIS
5 use strict;
6 use warnings;
7 use HTML::Parser ();
8
9 # Create parser object
10 my $p = HTML::Parser->new(
11 api_version => 3,
12 start_h => [\&start, "tagname, attr"],
13 end_h => [\&end, "tagname"],
14 marked_sections => 1,
15 );
16
17 # Parse document text chunk by chunk
18 $p->parse($chunk1);
19 $p->parse($chunk2);
20 # ...
21 # signal end of document
22 $p->eof;
23
24 # Parse directly from file
25 $p->parse_file("foo.html");
26 # or
27 open(my $fh, "<:utf8", "foo.html") || die;
28 $p->parse_file($fh);
29
30DESCRIPTION
31 Objects of the "HTML::Parser" class will recognize markup and separate
32 it from plain text (alias data content) in HTML documents. As different
33 kinds of markup and text are recognized, the corresponding event
34 handlers are invoked.
35
36 "HTML::Parser" is not a generic SGML parser. We have tried to make it
37 able to deal with the HTML that is actually "out there", and it normally
38 parses as closely as possible to the way the popular web browsers do it
39 instead of strictly following one of the many HTML specifications from
40 W3C. Where there is disagreement, there is often an option that you can
41 enable to get the official behaviour.
42
43 The document to be parsed may be supplied in arbitrary chunks. This
44 makes on-the-fly parsing as documents are received from the network
45 possible.
46
47 If event driven parsing does not feel right for your application, you
48 might want to use "HTML::PullParser". This is an "HTML::Parser" subclass
49 that allows a more conventional program structure.
50
51METHODS
52 The following method is used to construct a new "HTML::Parser" object:
53
54 $p = HTML::Parser->new( %options_and_handlers )
55 This class method creates a new "HTML::Parser" object and returns
56 it. Key/value argument pairs may be provided to assign event
57 handlers or initialize parser options. The handlers and parser
58 options can also be set or modified later by the method calls
59 described below.
60
61 If a top level key is in the form "<event>_h" (e.g., "text_h") then
62 it assigns a handler to that event, otherwise it initializes a
63 parser option. The event handler specification value must be an
64 array reference. Multiple handlers may also be assigned with the
65 'handlers => [%handlers]' option. See examples below.
66
67 If new() is called without any arguments, it will create a parser
68 that uses callback methods compatible with version 2 of
69 "HTML::Parser". See the section on "version 2 compatibility" below
70 for details.
71
72 The special constructor option 'api_version => 2' can be used to
73 initialize version 2 callbacks while still setting other options and
74 handlers. The 'api_version => 3' option can be used if you don't
75 want to set any options and don't want to fall back to v2 compatible
76 mode.
77
78 Examples:
79
80 $p = HTML::Parser->new(
81 api_version => 3,
82 text_h => [ sub {...}, "dtext" ]
83 );
84
85 This creates a new parser object with a text event handler
86 subroutine that receives the original text with general entities
87 decoded.
88
89 $p = HTML::Parser->new(
90 api_version => 3,
91 start_h => [ 'my_start', "self,tokens" ]
92 );
93
94 This creates a new parser object with a start event handler method
95 that receives the $p and the tokens array.
96
97 $p = HTML::Parser->new(
98 api_version => 3,
99 handlers => {
100 text => [\@array, "event,text"],
101 comment => [\@array, "event,text"],
102 }
103 );
104
105 This creates a new parser object that stores the event type and the
106 original text in @array for text and comment events.
107
108 The following methods feed the HTML document to the "HTML::Parser"
109 object:
110
111 $p->parse( $string )
112 Parse $string as the next chunk of the HTML document. Handlers
113 invoked should not attempt to modify the $string in-place until
114 $p->parse returns.
115
116 If an invoked event handler aborts parsing by calling $p->eof, then
117 $p->parse() will return a FALSE value. Otherwise the return value is
118 a reference to the parser object ($p).
119
120 $p->parse( $code_ref )
121 If a code reference is passed as the argument to be parsed, then the
122 chunks to be parsed are obtained by invoking this function
123 repeatedly. Parsing continues until the function returns an empty
124 (or undefined) result. When this happens $p->eof is automatically
125 signaled.
126
127 Parsing will also abort if one of the event handlers calls $p->eof.
128
129 The effect of this is the same as:
130
131 while (1) {
132 my $chunk = &$code_ref();
133 if (!defined($chunk) || !length($chunk)) {
134 $p->eof;
135 return $p;
136 }
137 $p->parse($chunk) || return undef;
138 }
139
140 But it is more efficient as this loop runs internally in XS code.
141
142 $p->parse_file( $file )
143 Parse text directly from a file. The $file argument can be a
144 filename, an open file handle, or a reference to an open file
145 handle.
146
147 If $file contains a filename and the file can't be opened, then the
148 method returns an undefined value and $! tells why it failed.
149 Otherwise the return value is a reference to the parser object.
150
151 If a file handle is passed as the $file argument, then the file will
152 normally be read until EOF, but not closed.
153
154 If an invoked event handler aborts parsing by calling $p->eof, then
155 $p->parse_file() may not have read the entire file.
156
157 On systems with multi-byte line terminators, the values passed for
158 the offset and length argspecs may be too low if parse_file() is
159 called on a file handle that is not in binary mode.
160
161 If a filename is passed in, then parse_file() will open the file in
162 binary mode.
163
164 $p->eof
165 Signals the end of the HTML document. Calling the $p->eof method
166 outside a handler callback will flush any remaining buffered text
167 (which triggers the "text" event if there is any remaining text).
168
169 Calling $p->eof inside a handler will terminate parsing at that
170 point and cause $p->parse to return a FALSE value. This also
171 terminates parsing by $p->parse_file().
172
173 After $p->eof has been called, the parse() and parse_file() methods
174 can be invoked to feed new documents with the parser object.
175
176 The return value from eof() is a reference to the parser object.
177
178 Most parser options are controlled by boolean attributes. Each boolean
179 attribute is enabled by calling the corresponding method with a TRUE
180 argument and disabled with a FALSE argument. The attribute value is left
181 unchanged if no argument is given. The return value from each method is
182 the old attribute value.
183
184 Methods that can be used to get and/or set parser options are:
185
186 $p->attr_encoded
187 $p->attr_encoded( $bool )
188 By default, the "attr" and @attr argspecs will have general entities
189 for attribute values decoded. Enabling this attribute leaves
190 entities alone.
191
192 $p->backquote
193 $p->backquote( $bool )
194 By default, only ' and " are recognized as quote characters around
195 attribute values. MSIE also recognizes backquotes for some reason.
196 Enabling this attribute provides compatibility with this behaviour.
197
198 $p->boolean_attribute_value( $val )
199 This method sets the value reported for boolean attributes inside
200 HTML start tags. By default, the name of the attribute is also used
201 as its value. This affects the values reported for "tokens" and
202 "attr" argspecs.
203
204 $p->case_sensitive
205 $p->case_sensitive( $bool )
206 By default, tag names and attribute names are down-cased. Enabling
207 this attribute leaves them as found in the HTML source document.
208
209 $p->closing_plaintext
210 $p->closing_plaintext( $bool )
211 By default, "plaintext" element can never be closed. Everything up
212 to the end of the document is parsed in CDATA mode. This historical
213 behaviour is what at least MSIE does. Enabling this attribute makes
214 closing " </plaintext" > tag effective and the parsing process will
215 resume after seeing this tag. This emulates early gecko-based
216 browsers.
217
218 $p->empty_element_tags
219 $p->empty_element_tags( $bool )
220 By default, empty element tags are not recognized as such and the
221 "/" before ">" is just treated like a normal name character (unless
222 "strict_names" is enabled). Enabling this attribute make
223 "HTML::Parser" recognize these tags.
224
225 Empty element tags look like start tags, but end with the character
226 sequence "/>" instead of ">". When recognized by "HTML::Parser" they
227 cause an artificial end event in addition to the start event. The
228 "text" for the artificial end event will be empty and the "tokenpos"
229 array will be undefined even though the token array will have one
230 element containing the tag name.
231
232 $p->marked_sections
233 $p->marked_sections( $bool )
234 By default, section markings like <![CDATA[...]]> are treated like
235 ordinary text. When this attribute is enabled section markings are
236 honoured.
237
238 There are currently no events associated with the marked section
239 markup, but the text can be returned as "skipped_text".
240
241 $p->strict_comment
242 $p->strict_comment( $bool )
243 By default, comments are terminated by the first occurrence of
244 "-->". This is the behaviour of most popular browsers (like Mozilla,
245 Opera and MSIE), but it is not correct according to the official
246 HTML standard. Officially, you need an even number of "--" tokens
247 before the closing ">" is recognized and there may not be anything
248 but whitespace between an even and an odd "--".
249
250 The official behaviour is enabled by enabling this attribute.
251
252 Enabling of 'strict_comment' also disables recognizing these forms
253 as comments:
254
255 </ comment>
256 <! comment>
257
258 $p->strict_end
259 $p->strict_end( $bool )
260 By default, attributes and other junk are allowed to be present on
261 end tags in a manner that emulates MSIE's behaviour.
262
263 The official behaviour is enabled with this attribute. If enabled,
264 only whitespace is allowed between the tagname and the final ">".
265
266 $p->strict_names
267 $p->strict_names( $bool )
268 By default, almost anything is allowed in tag and attribute names.
269 This is the behaviour of most popular browsers and allows us to
270 parse some broken tags with invalid attribute values like:
271
272 <IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0>
273
274 By default, "LIST]" is parsed as a boolean attribute, not as part of
275 the ALT value as was clearly intended. This is also what Mozilla
276 sees.
277
278 The official behaviour is enabled by enabling this attribute. If
279 enabled, it will cause the tag above to be reported as text since
280 "LIST]" is not a legal attribute name.
281
282 $p->unbroken_text
283 $p->unbroken_text( $bool )
284 By default, blocks of text are given to the text handler as soon as
285 possible (but the parser takes care always to break text at a
286 boundary between whitespace and non-whitespace so single words and
287 entities can always be decoded safely). This might create breaks
288 that make it hard to do transformations on the text. When this
289 attribute is enabled, blocks of text are always reported in one
290 piece. This will delay the text event until the following (non-text)
291 event has been recognized by the parser.
292
293 Note that the "offset" argspec will give you the offset of the first
294 segment of text and "length" is the combined length of the segments.
295 Since there might be ignored tags in between, these numbers can't be
296 used to directly index in the original document file.
297
298 $p->utf8_mode
299 $p->utf8_mode( $bool )
300 Enable this option when parsing raw undecoded UTF-8. This tells the
301 parser that the entities expanded for strings reported by "attr",
302 @attr and "dtext" should be expanded as decoded UTF-8 so they end up
303 compatible with the surrounding text.
304
305 If "utf8_mode" is enabled then it is an error to pass strings
306 containing characters with code above 255 to the parse() method, and
307 the parse() method will croak if you try.
308
309 Example: The Unicode character "\x{2665}" is "\xE2\x99\xA5" when
310 UTF-8 encoded. The character can also be represented by the entity
311 "♥" or "♥". If we feed the parser:
312
313 $p->parse("\xE2\x99\xA5♥");
314
315 then "dtext" will be reported as "\xE2\x99\xA5\x{2665}" without
316 "utf8_mode" enabled, but as "\xE2\x99\xA5\xE2\x99\xA5" when enabled.
317 The later string is what you want.
318
319 This option is only available with perl-5.8 or better.
320
321 $p->xml_mode
322 $p->xml_mode( $bool )
323 Enabling this attribute changes the parser to allow some XML
324 constructs. This enables the behaviour controlled by individually by
325 the "case_sensitive", "empty_element_tags", "strict_names" and
326 "xml_pic" attributes and also suppresses special treatment of
327 elements that are parsed as CDATA for HTML.
328
329 $p->xml_pic
330 $p->xml_pic( $bool )
331 By default, *processing instructions* are terminated by ">". When
332 this attribute is enabled, processing instructions are terminated by
333 "?>" instead.
334
335 As markup and text is recognized, handlers are invoked. The following
336 method is used to set up handlers for different events:
337
338 $p->handler( event => \&subroutine, $argspec )
339 $p->handler( event => $method_name, $argspec )
340 $p->handler( event => \@accum, $argspec )
341 $p->handler( event => "" );
342 $p->handler( event => undef );
343 $p->handler( event );
344 This method assigns a subroutine, method, or array to handle an
345 event.
346
347 Event is one of "text", "start", "end", "declaration", "comment",
348 "process", "start_document", "end_document" or "default".
349
350 The "\&subroutine" is a reference to a subroutine which is called to
351 handle the event.
352
353 The $method_name is the name of a method of $p which is called to
354 handle the event.
355
356 The @accum is an array that will hold the event information as
357 sub-arrays.
358
359 If the second argument is "", the event is ignored. If it is undef,
360 the default handler is invoked for the event.
361
362 The $argspec is a string that describes the information to be
363 reported for the event. Any requested information that does not
364 apply to a specific event is passed as "undef". If argspec is
365 omitted, then it is left unchanged.
366
367 The return value from $p->handler is the old callback routine or a
368 reference to the accumulator array.
369
370 Any return values from handler callback routines/methods are always
371 ignored. A handler callback can request parsing to be aborted by
372 invoking the $p->eof method. A handler callback is not allowed to
373 invoke the $p->parse() or $p->parse_file() method. An exception will
374 be raised if it tries.
375
376 Examples:
377
378 $p->handler(start => "start", 'self, attr, attrseq, text' );
379
380 This causes the "start" method of object $p to be called for 'start'
381 events. The callback signature is "$p->start(\%attr, \@attr_seq,
382 $text)".
383
384 $p->handler(start => \&start, 'attr, attrseq, text' );
385
386 This causes subroutine start() to be called for 'start' events. The
387 callback signature is start(\%attr, \@attr_seq, $text).
388
389 $p->handler(start => \@accum, '"S", attr, attrseq, text' );
390
391 This causes 'start' event information to be saved in @accum. The
392 array elements will be ['S', \%attr, \@attr_seq, $text].
393
394 $p->handler(start => "");
395
396 This causes 'start' events to be ignored. It also suppresses
397 invocations of any default handler for start events. It is in most
398 cases equivalent to $p->handler(start => sub {}), but is more
399 efficient. It is different from the empty-sub-handler in that
400 "skipped_text" is not reset by it.
401
402 $p->handler(start => undef);
403
404 This causes no handler to be associated with start events. If there
405 is a default handler it will be invoked.
406
407 Filters based on tags can be set up to limit the number of events
408 reported. The main bottleneck during parsing is often the huge number of
409 callbacks made from the parser. Applying filters can improve performance
410 significantly.
411
412 The following methods control filters:
413
414 $p->ignore_elements( @tags )
415 Both the "start" event and the "end" event as well as any events
416 that would be reported in between are suppressed. The ignored
417 elements can contain nested occurrences of itself. Example:
418
419 $p->ignore_elements(qw(script style));
420
421 The "script" and "style" tags will always nest properly since their
422 content is parsed in CDATA mode. For most other tags
423 "ignore_elements" must be used with caution since HTML is often not
424 *well formed*.
425
426 $p->ignore_tags( @tags )
427 Any "start" and "end" events involving any of the tags given are
428 suppressed. To reset the filter (i.e. don't suppress any "start" and
429 "end" events), call "ignore_tags" without an argument.
430
431 $p->report_tags( @tags )
432 Any "start" and "end" events involving any of the tags *not* given
433 are suppressed. To reset the filter (i.e. report all "start" and
434 "end" events), call "report_tags" without an argument.
435
436 Internally, the system has two filter lists, one for "report_tags" and
437 one for "ignore_tags", and both filters are applied. This effectively
438 gives "ignore_tags" precedence over "report_tags".
439
440 Examples:
441
442 $p->ignore_tags(qw(style));
443 $p->report_tags(qw(script style));
444
445 results in only "script" events being reported.
446
447 Argspec
448 Argspec is a string containing a comma-separated list that describes the
449 information reported by the event. The following argspec identifier
450 names can be used:
451
452 "attr"
453 Attr causes a reference to a hash of attribute name/value pairs to
454 be passed.
455
456 Boolean attributes' values are either the value set by
457 $p->boolean_attribute_value, or the attribute name if no value has
458 been set by $p->boolean_attribute_value.
459
460 This passes undef except for "start" events.
461
462 Unless "xml_mode" or "case_sensitive" is enabled, the attribute
463 names are forced to lower case.
464
465 General entities are decoded in the attribute values and one layer
466 of matching quotes enclosing the attribute values is removed.
467
468 The Unicode character set is assumed for entity decoding.
469
470 @attr
471 Basically the same as "attr", but keys and values are passed as
472 individual arguments and the original sequence of the attributes is
473 kept. The parameters passed will be the same as the @attr calculated
474 here:
475
476 @attr = map { $_ => $attr->{$_} } @$attrseq;
477
478 assuming $attr and $attrseq here are the hash and array passed as
479 the result of "attr" and "attrseq" argspecs.
480
481 This passes no values for events besides "start".
482
483 "attrseq"
484 Attrseq causes a reference to an array of attribute names to be
485 passed. This can be useful if you want to walk the "attr" hash in
486 the original sequence.
487
488 This passes undef except for "start" events.
489
490 Unless "xml_mode" or "case_sensitive" is enabled, the attribute
491 names are forced to lower case.
492
493 "column"
494 Column causes the column number of the start of the event to be
495 passed. The first column on a line is 0.
496
497 "dtext"
498 Dtext causes the decoded text to be passed. General entities are
499 automatically decoded unless the event was inside a CDATA section or
500 was between literal start and end tags ("script", "style", "xmp",
501 "iframe", "title", "textarea" and "plaintext").
502
503 The Unicode character set is assumed for entity decoding. With Perl
504 version 5.6 or earlier only the Latin-1 range is supported, and
505 entities for characters outside the range 0..255 are left unchanged.
506
507 This passes undef except for "text" events.
508
509 "event"
510 Event causes the event name to be passed.
511
512 The event name is one of "text", "start", "end", "declaration",
513 "comment", "process", "start_document" or "end_document".
514
515 "is_cdata"
516 Is_cdata causes a TRUE value to be passed if the event is inside a
517 CDATA section or between literal start and end tags ("script",
518 "style", "xmp", "iframe", "title", "textarea" and "plaintext").
519
520 if the flag is FALSE for a text event, then you should normally
521 either use "dtext" or decode the entities yourself before the text
522 is processed further.
523
524 "length"
525 Length causes the number of bytes of the source text of the event to
526 be passed.
527
528 "line"
529 Line causes the line number of the start of the event to be passed.
530 The first line in the document is 1. Line counting doesn't start
531 until at least one handler requests this value to be reported.
532
533 "offset"
534 Offset causes the byte position in the HTML document of the start of
535 the event to be passed. The first byte in the document has offset 0.
536
537 "offset_end"
538 Offset_end causes the byte position in the HTML document of the end
539 of the event to be passed. This is the same as "offset" + "length".
540
541 "self"
542 Self causes the current object to be passed to the handler. If the
543 handler is a method, this must be the first element in the argspec.
544
545 An alternative to passing self as an argspec is to register closures
546 that capture $self by themselves as handlers. Unfortunately this
547 creates circular references which prevent the HTML::Parser object
548 from being garbage collected. Using the "self" argspec avoids this
549 problem.
550
551 "skipped_text"
552 Skipped_text returns the concatenated text of all the events that
553 have been skipped since the last time an event was reported. Events
554 might be skipped because no handler is registered for them or
555 because some filter applies. Skipped text also includes marked
556 section markup, since there are no events that can catch it.
557
558 If an ""-handler is registered for an event, then the text for this
559 event is not included in "skipped_text". Skipped text both before
560 and after the ""-event is included in the next reported
561 "skipped_text".
562
563 "tag"
564 Same as "tagname", but prefixed with "/" if it belongs to an "end"
565 event and "!" for a declaration. The "tag" does not have any prefix
566 for "start" events, and is in this case identical to "tagname".
567
568 "tagname"
569 This is the element name (or *generic identifier* in SGML jargon)
570 for start and end tags. Since HTML is case insensitive, this name is
571 forced to lower case to ease string matching.
572
573 Since XML is case sensitive, the tagname case is not changed when
574 "xml_mode" is enabled. The same happens if the "case_sensitive"
575 attribute is set.
576
577 The declaration type of declaration elements is also passed as a
578 tagname, even if that is a bit strange. In fact, in the current
579 implementation tagname is identical to "token0" except that the name
580 may be forced to lower case.
581
582 "token0"
583 Token0 causes the original text of the first token string to be
584 passed. This should always be the same as $tokens->[0].
585
586 For "declaration" events, this is the declaration type.
587
588 For "start" and "end" events, this is the tag name.
589
590 For "process" and non-strict "comment" events, this is everything
591 inside the tag.
592
593 This passes undef if there are no tokens in the event.
594
595 "tokenpos"
596 Tokenpos causes a reference to an array of token positions to be
597 passed. For each string that appears in "tokens", this array
598 contains two numbers. The first number is the offset of the start of
599 the token in the original "text" and the second number is the length
600 of the token.
601
602 Boolean attributes in a "start" event will have (0,0) for the
603 attribute value offset and length.
604
605 This passes undef if there are no tokens in the event (e.g., "text")
606 and for artificial "end" events triggered by empty element tags.
607
608 If you are using these offsets and lengths to modify "text", you
609 should either work from right to left, or be very careful to
610 calculate the changes to the offsets.
611
612 "tokens"
613 Tokens causes a reference to an array of token strings to be passed.
614 The strings are exactly as they were found in the original text, no
615 decoding or case changes are applied.
616
617 For "declaration" events, the array contains each word, comment, and
618 delimited string starting with the declaration type.
619
620 For "comment" events, this contains each sub-comment. If
621 $p->strict_comments is disabled, there will be only one sub-comment.
622
623 For "start" events, this contains the original tag name followed by
624 the attribute name/value pairs. The values of boolean attributes
625 will be either the value set by $p->boolean_attribute_value, or the
626 attribute name if no value has been set by
627 $p->boolean_attribute_value.
628
629 For "end" events, this contains the original tag name (always one
630 token).
631
632 For "process" events, this contains the process instructions (always
633 one token).
634
635 This passes "undef" for "text" events.
636
637 "text"
638 Text causes the source text (including markup element delimiters) to
639 be passed.
640
641 "undef"
642 Pass an undefined value. Useful as padding where the same handler
643 routine is registered for multiple events.
644
645 '...'
646 A literal string of 0 to 255 characters enclosed in single (') or
647 double (") quotes is passed as entered.
648
649 The whole argspec string can be wrapped up in '@{...}' to signal that
650 the resulting event array should be flattened. This only makes a
651 difference if an array reference is used as the handler target. Consider
652 this example:
653
654 $p->handler(text => [], 'text');
655 $p->handler(text => [], '@{text}']);
656
657 With two text events; "foo", "bar"; then the first example will end up
658 with [["foo"], ["bar"]] and the second with ["foo", "bar"] in the
659 handler target array.
660
661 Events
662 Handlers for the following events can be registered:
663
664 "comment"
665 This event is triggered when a markup comment is recognized.
666
667 Example:
668
669 <!-- This is a comment -- -- So is this -->
670
671 "declaration"
672 This event is triggered when a *markup declaration* is recognized.
673
674 For typical HTML documents, the only declaration you are likely to
675 find is <!DOCTYPE ...>.
676
677 Example:
678
679 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
680 "http://www.w3.org/TR/html4/strict.dtd">
681
682 DTDs inside <!DOCTYPE ...> will confuse HTML::Parser.
683
684 "default"
685 This event is triggered for events that do not have a specific
686 handler. You can set up a handler for this event to catch stuff you
687 did not want to catch explicitly.
688
689 "end"
690 This event is triggered when an end tag is recognized.
691
692 Example:
693
694 </A>
695
696 "end_document"
697 This event is triggered when $p->eof is called and after any
698 remaining text is flushed. There is no document text associated with
699 this event.
700
701 "process"
702 This event is triggered when a processing instructions markup is
703 recognized.
704
705 The format and content of processing instructions are system and
706 application dependent.
707
708 Examples:
709
710 <? HTML processing instructions >
711 <? XML processing instructions ?>
712
713 "start"
714 This event is triggered when a start tag is recognized.
715
716 Example:
717
718 <A HREF="http://www.perl.com/">
719
720 "start_document"
721 This event is triggered before any other events for a new document.
722 A handler for it can be used to initialize stuff. There is no
723 document text associated with this event.
724
725 "text"
726 This event is triggered when plain text (characters) is recognized.
727 The text may contain multiple lines. A sequence of text may be
728 broken between several text events unless $p->unbroken_text is
729 enabled.
730
731 The parser will make sure that it does not break a word or a
732 sequence of whitespace between two text events.
733
734 Unicode
735 "HTML::Parser" can parse Unicode strings when running under perl-5.8 or
736 better. If Unicode is passed to $p->parse() then chunks of Unicode will
737 be reported to the handlers. The offset and length argspecs will also
738 report their position in terms of characters.
739
740 It is safe to parse raw undecoded UTF-8 if you either avoid decoding
741 entities and make sure to not use *argspecs* that do, or enable the
742 "utf8_mode" for the parser. Parsing of undecoded UTF-8 might be useful
743 when parsing from a file where you need the reported offsets and lengths
744 to match the byte offsets in the file.
745
746 If a filename is passed to $p->parse_file() then the file will be read
747 in binary mode. This will be fine if the file contains only ASCII or
748 Latin-1 characters. If the file contains UTF-8 encoded text then care
749 must be taken when decoding entities as described in the previous
750 paragraph, but better is to open the file with the UTF-8 layer so that
751 it is decoded properly:
752
753 open(my $fh, "<:utf8", "index.html") || die "...: $!";
754 $p->parse_file($fh);
755
756 If the file contains text encoded in a charset besides ASCII, Latin-1 or
757 UTF-8 then decoding will always be needed.
758
759VERSION 2 COMPATIBILITY
760 When an "HTML::Parser" object is constructed with no arguments, a set of
761 handlers is automatically provided that is compatible with the old
762 HTML::Parser version 2 callback methods.
763
764 This is equivalent to the following method calls:
765
766 $p->handler(start => "start", "self, tagname, attr, attrseq, text");
767 $p->handler(end => "end", "self, tagname, text");
768 $p->handler(text => "text", "self, text, is_cdata");
769 $p->handler(process => "process", "self, token0, text");
770 $p->handler(
771 comment => sub {
772 my($self, $tokens) = @_;
773 for (@$tokens) {$self->comment($_);}
774 },
775 "self, tokens"
776 );
777 $p->handler(
778 declaration => sub {
779 my $self = shift;
780 $self->declaration(substr($_[0], 2, -1));
781 },
782 "self, text"
783 );
784
785 Setting up these handlers can also be requested with the "api_version =>
786 2" constructor option.
787
788SUBCLASSING
789 The "HTML::Parser" class is able to be subclassed. Parser objects are
790 plain hashes and "HTML::Parser" reserves only hash keys that start with
791 "_hparser". The parser state can be set up by invoking the init()
792 method, which takes the same arguments as new().
793
794EXAMPLES
795 The first simple example shows how you might strip out comments from an
796 HTML document. We achieve this by setting up a comment handler that does
797 nothing and a default handler that will print out anything else:
798
799 use HTML::Parser;
800 HTML::Parser->new(
801 default_h => [sub { print shift }, 'text'],
802 comment_h => [""],
803 )->parse_file(shift || die) || die $!;
804
805 An alternative implementation is:
806
807 use HTML::Parser;
808 HTML::Parser->new(
809 end_document_h => [sub { print shift }, 'skipped_text'],
810 comment_h => [""],
811 )->parse_file(shift || die) || die $!;
812
813 This will in most cases be much more efficient since only a single
814 callback will be made.
815
816 The next example prints out the text that is inside the <title> element
817 of an HTML document. Here we start by setting up a start handler. When
818 it sees the title start tag it enables a text handler that prints any
819 text found and an end handler that will terminate parsing as soon as the
820 title end tag is seen:
821
822 use HTML::Parser ();
823
824 sub start_handler {
825 return if shift ne "title";
826 my $self = shift;
827 $self->handler(text => sub { print shift }, "dtext");
828 $self->handler(
829 end => sub {
830 shift->eof if shift eq "title";
831 },
832 "tagname,self"
833 );
834 }
835
836 my $p = HTML::Parser->new(api_version => 3);
837 $p->handler(start => \&start_handler, "tagname,self");
838 $p->parse_file(shift || die) || die $!;
839 print "\n";
840
841 More examples are found in the eg/ directory of the "HTML-Parser"
842 distribution: the program "hrefsub" shows how you can edit all links
843 found in a document; the program "htextsub" shows how to edit the text
844 only; the program "hstrip" shows how you can strip out certain
845 tags/elements and/or attributes; and the program "htext" show how to
846 obtain the plain text, but not any script/style content.
847
848 You can browse the eg/ directory online from the *[Browse]* link on the
849 http://search.cpan.org/~gaas/HTML-Parser/ page.
850
851BUGS
852 The <style> and <script> sections do not end with the first "</", but
853 need the complete corresponding end tag. The standard behaviour is not
854 really practical.
855
856 When the *strict_comment* option is enabled, we still recognize comments
857 where there is something other than whitespace between even and odd "--"
858 markers.
859
860 Once $p->boolean_attribute_value has been set, there is no way to
861 restore the default behaviour.
862
863 There is currently no way to get both quote characters into the same
864 literal argspec.
865
866 Empty tags, e.g. "<>" and "</>", are not recognized. SGML allows them to
867 repeat the previous start tag or close the previous start tag
868 respectively.
869
870 NET tags, e.g. "code/.../" are not recognized. This is SGML shorthand
871 for "<code>...</code>".
872
873 Incomplete start or end tags, e.g. "<tt<b>...</b</tt>" are not
874 recognized.
875
876DIAGNOSTICS
877 The following messages may be produced by HTML::Parser. The notation in
878 this listing is the same as used in perldiag:
879
880 Not a reference to a hash
881 (F) The object blessed into or subclassed from HTML::Parser is not a
882 hash as required by the HTML::Parser methods.
883
884 Bad signature in parser state object at %p
885 (F) The _hparser_xs_state element does not refer to a valid state
886 structure. Something must have changed the internal value stored in
887 this hash element, or the memory has been overwritten.
888
889 _hparser_xs_state element is not a reference
890 (F) The _hparser_xs_state element has been destroyed.
891
892 Can't find '_hparser_xs_state' element in HTML::Parser hash
893 (F) The _hparser_xs_state element is missing from the parser hash.
894 It was either deleted, or not created when the object was created.
895
896 API version %s not supported by HTML::Parser %s
897 (F) The constructor option 'api_version' with an argument greater
898 than or equal to 4 is reserved for future extensions.
899
900 Bad constructor option '%s'
901 (F) An unknown constructor option key was passed to the new() or
902 init() methods.
903
904 Parse loop not allowed
905 (F) A handler invoked the parse() or parse_file() method. This is
906 not permitted.
907
908 marked sections not supported
909 (F) The $p->marked_sections() method was invoked in a HTML::Parser
910 module that was compiled without support for marked sections.
911
912 Unknown boolean attribute (%d)
913 (F) Something is wrong with the internal logic that set up aliases
914 for boolean attributes.
915
916 Only code or array references allowed as handler
917 (F) The second argument for $p->handler must be either a subroutine
918 reference, then name of a subroutine or method, or a reference to an
919 array.
920
921 No handler for %s events
922 (F) The first argument to $p->handler must be a valid event name;
923 i.e. one of "start", "end", "text", "process", "declaration" or
924 "comment".
925
926 Unrecognized identifier %s in argspec
927 (F) The identifier is not a known argspec name. Use one of the names
928 mentioned in the argspec section above.
929
930 Literal string is longer than 255 chars in argspec
931 (F) The current implementation limits the length of literals in an
932 argspec to 255 characters. Make the literal shorter.
933
934 Backslash reserved for literal string in argspec
935 (F) The backslash character "\" is not allowed in argspec literals.
936 It is reserved to permit quoting inside a literal in a later
937 version.
938
939 Unterminated literal string in argspec
940 (F) The terminating quote character for a literal was not found.
941
942 Bad argspec (%s)
943 (F) Only identifier names, literals, spaces and commas are allowed
944 in argspecs.
945
946 Missing comma separator in argspec
947 (F) Identifiers in an argspec must be separated with ",".
948
949 Parsing of undecoded UTF-8 will give garbage when decoding entities
950 (W) The first chunk parsed appears to contain undecoded UTF-8 and
951 one or more argspecs that decode entities are used for the callback
952 handlers.
953
954 The result of decoding will be a mix of encoded and decoded
955 characters for any entities that expand to characters with code
956 above 127. This is not a good thing.
957
958 The recommended solution is to apply Encode::decode_utf8() on the
959 data before feeding it to the $p->parse(). For $p->parse_file() pass
960 a file that has been opened in ":utf8" mode.
961
962 The alternative solution is to enable the "utf8_mode" and not decode
963 before passing strings to $p->parse(). The parser can process raw
964 undecoded UTF-8 sanely if the "utf8_mode" is enabled, or if the
965 "attr", @attr or "dtext" argspecs are avoided.
966
967 Parsing string decoded with wrong endian selection
968 (W) The first character in the document is U+FFFE. This is not a
969 legal Unicode character but a byte swapped "BOM". The result of
970 parsing will likely be garbage.
971
972 Parsing of undecoded UTF-32
973 (W) The parser found the Unicode UTF-32 "BOM" signature at the start
974 of the document. The result of parsing will likely be garbage.
975
976 Parsing of undecoded UTF-16
977 (W) The parser found the Unicode UTF-16 "BOM" signature at the start
978 of the document. The result of parsing will likely be garbage.
979
980SEE ALSO
981 HTML::Entities, HTML::PullParser, HTML::TokeParser, HTML::HeadParser,
982 HTML::LinkExtor, HTML::Form
983
984 HTML::TreeBuilder (part of the *HTML-Tree* distribution)
985
986 <http://www.w3.org/TR/html4/>
987
988 More information about marked sections and processing instructions may
989 be found at <http://www.is-thought.co.uk/book/sgml-8.htm>.
990
991COPYRIGHT
992 Copyright 1996-2016 Gisle Aas. All rights reserved.
993 Copyright 1999-2000 Michael A. Chase. All rights reserved.
994
995 This library is free software; you can redistribute it and/or modify it
996 under the same terms as Perl itself.
997
998