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