Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1090 lines
34 KiB

  1. package HTML::Parser;
  2. # Copyright 1996-2001, Gisle Aas.
  3. # Copyright 1999-2000, Michael A. Chase.
  4. #
  5. # This library is free software; you can redistribute it and/or
  6. # modify it under the same terms as Perl itself.
  7. use strict;
  8. use vars qw($VERSION @ISA);
  9. $VERSION = '3.25'; # $Date: 2001/05/11 17:24:09 $
  10. require HTML::Entities;
  11. require DynaLoader;
  12. @ISA=qw(DynaLoader);
  13. HTML::Parser->bootstrap($VERSION);
  14. sub new
  15. {
  16. my $class = shift;
  17. my $self = bless {}, $class;
  18. return $self->init(@_);
  19. }
  20. sub init
  21. {
  22. my $self = shift;
  23. $self->_alloc_pstate;
  24. my %arg = @_;
  25. my $api_version = delete $arg{api_version} || (@_ ? 3 : 2);
  26. if ($api_version >= 4) {
  27. require Carp;
  28. Carp::croak("API version $api_version not supported " .
  29. "by HTML::Parser $VERSION");
  30. }
  31. if ($api_version < 3) {
  32. # Set up method callbacks compatible with HTML-Parser-2.xx
  33. $self->handler(text => "text", "self,text,is_cdata");
  34. $self->handler(end => "end", "self,tagname,text");
  35. $self->handler(process => "process", "self,token0,text");
  36. $self->handler(start => "start",
  37. "self,tagname,attr,attrseq,text");
  38. $self->handler(comment =>
  39. sub {
  40. my($self, $tokens) = @_;
  41. for (@$tokens) {
  42. $self->comment($_);
  43. }
  44. }, "self,tokens");
  45. $self->handler(declaration =>
  46. sub {
  47. my $self = shift;
  48. $self->declaration(substr($_[0], 2, -1));
  49. }, "self,text");
  50. }
  51. if (my $h = delete $arg{handlers}) {
  52. $h = {@$h} if ref($h) eq "ARRAY";
  53. while (my($event, $cb) = each %$h) {
  54. $self->handler($event => @$cb);
  55. }
  56. }
  57. # In the end we try to assume plain attribute or handler
  58. while (my($option, $val) = each %arg) {
  59. if ($option =~ /^(\w+)_h$/) {
  60. $self->handler($1 => @$val);
  61. }
  62. elsif ($option =~ /^(text|start|end|process|declaration|comment)$/) {
  63. require Carp;
  64. Carp::croak("Bad constructor option '$option'");
  65. }
  66. else {
  67. $self->$option($val);
  68. }
  69. }
  70. return $self;
  71. }
  72. sub parse_file
  73. {
  74. my($self, $file) = @_;
  75. my $opened;
  76. if (!ref($file) && ref(\$file) ne "GLOB") {
  77. # Assume $file is a filename
  78. local(*F);
  79. open(F, $file) || return undef;
  80. binmode(F); # should we? good for byte counts
  81. $opened++;
  82. $file = *F;
  83. }
  84. my $chunk = '';
  85. while (read($file, $chunk, 512)) {
  86. $self->parse($chunk) || last;
  87. }
  88. close($file) if $opened;
  89. $self->eof;
  90. }
  91. sub netscape_buggy_comment # legacy
  92. {
  93. my $self = shift;
  94. require Carp;
  95. Carp::carp("netscape_buggy_comment() is deprecated. " .
  96. "Please use the strict_comment() method instead");
  97. my $old = !$self->strict_comment;
  98. $self->strict_comment(!shift) if @_;
  99. return $old;
  100. }
  101. # set up method stubs
  102. sub text { }
  103. *start = \&text;
  104. *end = \&text;
  105. *comment = \&text;
  106. *declaration = \&text;
  107. *process = \&text;
  108. 1;
  109. __END__
  110. =head1 NAME
  111. HTML::Parser - HTML parser class
  112. =head1 SYNOPSIS
  113. use HTML::Parser ();
  114. # Create parser object
  115. $p = HTML::Parser->new( api_version => 3,
  116. start_h => [\&start, "tagname, attr"],
  117. end_h => [\&end, "tagname"],
  118. marked_sections => 1,
  119. );
  120. # Parse document text chunk by chunk
  121. $p->parse($chunk1);
  122. $p->parse($chunk2);
  123. #...
  124. $p->eof; # signal end of document
  125. # Parse directly from file
  126. $p->parse_file("foo.html");
  127. # or
  128. open(F, "foo.html") || die;
  129. $p->parse_file(*F);
  130. HTML::Parser version 2 style subclassing and method callbacks:
  131. {
  132. package MyParser;
  133. use base 'HTML::Parser';
  134. sub start {
  135. my($self, $tagname, $attr, $attrseq, $origtext) = @_;
  136. #...
  137. }
  138. sub end {
  139. my($self, $tagname, $origtext) = @_;
  140. #...
  141. }
  142. sub text {
  143. my($self, $origtext, $is_cdata) = @_;
  144. #...
  145. }
  146. }
  147. my $p = MyParser->new;
  148. $p->parse_file("foo.html");
  149. =head1 DESCRIPTION
  150. Objects of the C<HTML::Parser> class will recognize markup and
  151. separate it from plain text (alias data content) in HTML
  152. documents. As different kinds of markup and text are recognized, the
  153. corresponding event handlers are invoked.
  154. C<HTML::Parser> in not a generic SGML parser. We have tried to
  155. make it able to deal with the HTML that is actually "out there", and
  156. it normally parses as closely as possible to the way the popular web
  157. browsers do it instead of strictly following one of the many HTML
  158. specifications from W3C. Where there is disagreement there is often
  159. an option that you can enable to get the official behaviour.
  160. The document to be parsed may be supplied in arbitrary chunks. This
  161. makes on-the-fly parsing as documents are received from the network
  162. possible.
  163. If event driven parsing does not feel right for your application, you
  164. might want to use C<HTML::PullParser>. It is a
  165. C<HTML::Parser> subclass that allows a more conventional program
  166. structure.
  167. =head1 METHODS
  168. The following method is used to construct a new C<HTML::Parser> object:
  169. =over
  170. =item $p = HTML::Parser->new( %options_and_handlers )
  171. This class method creates a new C<HTML::Parser> object and
  172. returns it. Key/value pair arguments may be provided to assign event
  173. handlers or initialize parser options. The handlers and parser
  174. options can also be set or modified later by method calls described below.
  175. If a top level key is in the form "<event>_h" (e.g., "text_h"} then it
  176. assigns a handler to that event, otherwise it initializes a parser
  177. option. The event handler specification value must be an array
  178. reference. Multiple handlers may also be assigned with the 'handlers
  179. => [%handlers]' option. See examples below.
  180. If new() is called without any arguments, it will create a parser that
  181. uses callback methods compatible with version 2 of C<HTML::Parser>.
  182. See the section on "version 2 compatibility" below for details.
  183. Special constructor option 'api_version => 2' can be used to
  184. initialize version 2 callbacks while still setting other options and
  185. handlers. The 'api_version => 3' option can be used if you don't want
  186. to set any options and don't want to fall back to v2 compatible
  187. mode.
  188. Examples:
  189. $p = HTML::Parser->new(api_version => 3,
  190. text_h => [ sub {...}, "dtext" ]);
  191. This creates a new parser object with a text event handler subroutine
  192. that receives the original text with general entities decoded.
  193. $p = HTML::Parser->new(api_version => 3,
  194. start_h => [ 'my_start', "self,tokens" ]);
  195. This creates a new parser object with a start event handler method
  196. that receives the $p and the tokens array.
  197. $p = HTML::Parser->new(api_version => 3,
  198. handlers => { text => [\@array, "event,text"],
  199. comment => [\@array, "event,text"],
  200. });
  201. This creates a new parser object that stores the event type and the
  202. original text in @array for text and comment events.
  203. =back
  204. The following methods feed the HTML document
  205. to the C<HTML::Parser> object:
  206. =over
  207. =item $p->parse( $string )
  208. Parse $string as the next chunk of the HTML document. The return
  209. value is normally a reference to the parser object (i.e. $p).
  210. Handlers invoked should not attempt modify the $string in-place until
  211. $p->parse returns.
  212. If an invoked event handler aborts parsing by calling $p->eof, then
  213. $p->parse() will return a FALSE value.
  214. =item $p->parse( $code_ref )
  215. If a code reference is passed in as the argument to parse then the
  216. chunks to parse is obtained by invoking this function repeatedly.
  217. Parsing continues until the function returns an empty (or undefined)
  218. result. When this happens $p->eof is automatically signalled.
  219. Parsing will also abort if one of the event handlers call $p->eof.
  220. The effect of this is the same as:
  221. while (1) {
  222. my $chunk = &$code_ref();
  223. if (!defined($chunk) || !length($chunk)) {
  224. $p->eof;
  225. return $p;
  226. }
  227. $p->parse($chunk) || return undef;
  228. }
  229. But it is more efficient as this loop runs internally in XS code.
  230. =item $p->parse_file( $file )
  231. Parse text directly from a file. The $file argument can be a
  232. filename, an open file handle, or a reference to a an open file
  233. handle.
  234. If $file contains a filename and the file can't be opened, then the
  235. method returns an undefined value and $! tells why it failed.
  236. Otherwise the return value is a reference to the parser object.
  237. If a file handle is passed as the $file argument, then the file will
  238. normally be read until EOF, but not closed.
  239. If an invoked event handler aborts parsing by calling $p->eof,
  240. then $p->parse_file() may not have read the entire file.
  241. On systems with multi-byte line terminators, the values passed for the
  242. offset and length argspecs may be too low if parse_file() is called on
  243. a file handle that is not in binary mode.
  244. If a filename is passed in, then parse_file() will open the file in
  245. binary mode.
  246. =item $p->eof
  247. Signals the end of the HTML document. Calling the $p->eof method
  248. outside a handler callback will flush any remaining buffered text
  249. (which triggers the C<text> event if there is any remaining text).
  250. Calling $p->eof inside a handler will terminate parsing at that point
  251. and cause $p->parse to return a FALSE value. This also terminates
  252. parsing by $p->parse_file().
  253. After $p->eof has been called, the parse() and parse_file() methods
  254. can be invoked to feed new documents with the parser object.
  255. The return value from eof() is a reference to the parser object.
  256. =back
  257. Most parser options are controlled by boolean attributes.
  258. Each boolean attribute is enabled by calling the corresponding method
  259. with a TRUE argument and disabled with a FALSE argument. The
  260. attribute value is left unchanged if no argument is given. The return
  261. value from each method is the old attribute value.
  262. Methods that can be used to get and/or set parser options are:
  263. =over
  264. =item $p->strict_comment( [$bool] )
  265. By default, comments are terminated by the first occurrence of "-->".
  266. This is the behaviour of most popular browsers (like Netscape and
  267. MSIE), but it is not correct according to the official HTML
  268. standard. Officially, you need an even number of "--" tokens before
  269. the closing ">" is recognized and there may not be anything but
  270. whitespace between an even and an odd "--".
  271. The official behaviour is enabled by enabling this attribute.
  272. =item $p->strict_names( [$bool] )
  273. By default, almost anything is allowed in tag and attribute names.
  274. This is the behaviour of most popular browsers and allows us to parse
  275. some broken tags with invalid attr values like:
  276. <IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0>
  277. By default, "LIST]" is parsed as a boolean attribute, not as
  278. part of the ALT value as was clearly intended. This is also what
  279. Netscape sees.
  280. The official behaviour is enabled by enabling this attribute. If
  281. enabled, it will cause the tag above to be reported as text
  282. since "LIST]" is not a legal attribute name.
  283. =item $p->boolean_attribute_value( $val )
  284. This method sets the value reported for boolean attributes inside HTML
  285. start tags. By default, the name of the attribute is also used as its
  286. value. This affects the values reported for C<tokens> and C<attr>
  287. argspecs.
  288. =item $p->xml_mode( [$bool] )
  289. Enabling this attribute changes the parser to allow some XML
  290. constructs such as I<empty element tags> and I<XML processing
  291. instructions>. It disables forcing tag and attribute names to lower
  292. case when they are reported by the C<tagname> and C<attr> argspecs,
  293. and suppress special treatment of elements that are parsed as CDATA
  294. for HTML.
  295. I<Empty element tags> look like start tags, but end with the character
  296. sequence "/>". When recognized by C<HTML::Parser> they cause an
  297. artificial end event in addition to the start event. The C<text> for
  298. the artificial end event will be empty and the C<tokenpos> array will
  299. be undefined even though the only element in the token array will have
  300. the correct tag name.
  301. I<XML processing instructions> are terminated by "?>" instead of a
  302. simple ">" as is the case for HTML.
  303. =item $p->unbroken_text( [$bool] )
  304. By default, blocks of text are given to the text handler as soon as
  305. possible (but the parser makes sure to always break text at the
  306. boundary between whitespace and non-whitespace so single words and
  307. entities always can be decoded safely). This might create breaks that
  308. make it hard to do transformations on the text. When this attribute is
  309. enabled, blocks of text are always reported in one piece. This will
  310. delay the text event until the following (non-text) event has been
  311. recognized by the parser.
  312. Note that the C<offset> argspec will give you the offset of the first
  313. segment of text and C<length> is the combined length of the segments.
  314. Since there might be ignored tags in between, these numbers can't be
  315. used to directly index in the original document file.
  316. =item $p->marked_sections( [$bool] )
  317. By default, section markings like <![CDATA[...]]> are treated like
  318. ordinary text. When this attribute is enabled section markings are
  319. honoured.
  320. There are currently no events associated with the marked section
  321. markup, but the text can be returned as C<skipped_text>.
  322. =back
  323. As markup and text is recognized, handlers are invoked. The following
  324. method is used to set up handlers for different events:
  325. =over
  326. =item $p->handler( event => \&subroutine, argspec )
  327. =item $p->handler( event => method_name, argspec )
  328. =item $p->handler( event => \@accum, argspec )
  329. =item $p->handler( event => "" );
  330. =item $p->handler( event => undef );
  331. =item $p->handler( event );
  332. This method assigns a subroutine, method, or array to handle an event.
  333. Event is one of C<text>, C<start>, C<end>, C<declaration>, C<comment>,
  334. C<process>, C<start_document>, C<end_document> or C<default>.
  335. I<Subroutine> is a reference to a subroutine which is called to handle
  336. the event.
  337. I<Method_name> is the name of a method of $p which is called to handle
  338. the event.
  339. I<Accum> is a array that will hold the event information as
  340. sub-arrays.
  341. If the second argument is "", the event is ignored.
  342. If it is undef, the default handler is invoked for the event.
  343. I<Argspec> is a string that describes the information to be reported
  344. for the event. Any requested information that does not apply to a
  345. specific event is passed as C<undef>. If argspec is omitted, then it
  346. is left unchanged since last update.
  347. The return value from $p->handle is the old callback routine or a
  348. reference to the accumulator array.
  349. Any return values from handler callback routines/methods are always
  350. ignored. A handler callback can request parsing to be aborted by
  351. invoking the $p->eof method. A handler callback is not allowed to
  352. invoke the $p->parse() or $p->parse_file() method. An exception will
  353. be raised if it tries.
  354. Examples:
  355. $p->handler(start => "start", 'self, attr, attrseq, text' );
  356. This causes the "start" method of object $p to be called for 'start' events.
  357. The callback signature is $p->start(\%attr, \@attr_seq, $text).
  358. $p->handler(start => \&start, 'attr, attrseq, text' );
  359. This causes subroutine start() to be called for 'start' events.
  360. The callback signature is start(\%attr, \@attr_seq, $text).
  361. $p->handler(start => \@accum, '"S", attr, attrseq, text' );
  362. This causes 'start' event information to be saved in @accum.
  363. The array elements will be ['S', \%attr, \@attr_seq, $text].
  364. $p->handler(start => "");
  365. This causes 'start' events to be ignored. It also supresses
  366. invokations of any default handler for start events. It is in most
  367. cases equivalent to $p->handler(start => sub {}), but is more
  368. efficient. It is different from the empty-sub-handler in that
  369. C<skipped_text> is not reset by it.
  370. $p->handler(start => undef);
  371. This causes no handler to be assosiated with start events.
  372. If there is a default handler it will be invoked.
  373. =back
  374. Filters based on tags can be set up to limit the number of events
  375. reported. The main bottleneck during parsing is often the huge number
  376. of callbacks made from the parser. Applying filters can improve
  377. performance significantly.
  378. The following methods control filters:
  379. =over
  380. =item $p->ignore_tags( TAG, ... )
  381. Any C<start> and C<end> events involving any of the tags given are
  382. suppressed.
  383. =item $p->report_tags( TAG, ... )
  384. Any C<start> and C<end> events involving any of the tags I<not> given
  385. are suppressed.
  386. =item $p->ignore_elements( TAG, ... )
  387. Both the C<start> and the C<end> event as well as any events that
  388. would be reported in between are suppressed. The ignored elements can
  389. contain nested occurences of itself. Example:
  390. $p->ignore_elements(qw(script style));
  391. The C<script> and C<style> tags will always nest properly since their
  392. content is parsed in CDATA mode. For most other tags
  393. C<ignore_elements> must be used with caution since HTML is often not
  394. I<well formed>.
  395. =back
  396. =head2 Argspec
  397. Argspec is a string containing a comma separated list that describes
  398. the information reported by the event. The following argspec
  399. identifier names can be used:
  400. =over
  401. =item C<self>
  402. Self causes the current object to be passed to the handler. If the
  403. handler is a method, this must be the first element in the argspec.
  404. An alternative to passing self as an argspec is to register closures
  405. that capture $self by themselves as handlers. Unfortunately this
  406. creates a circular references which prevents the HTML::Parser object
  407. from being garbage collected. Using the C<self> argspec avoids this
  408. problem.
  409. =item C<tokens>
  410. Tokens causes a reference to an array of token strings to be passed.
  411. The strings are exactly as they were found in the original text,
  412. no decoding or case changes are applied.
  413. For C<declaration> events, the array contains each word, comment, and
  414. delimited string starting with the declaration type.
  415. For C<comment> events, this contains each sub-comment. If
  416. $p->strict_comments is disabled, there will be only one sub-comment.
  417. For C<start> events, this contains the original tag name followed by
  418. the attribute name/value pairs. The value of boolean attributes will
  419. be either the value set by $p->boolean_attribute_value or the
  420. attribute name if no value has been set by
  421. $p->boolean_attribute_value.
  422. For C<end> events, this contains the original tag name (always one token).
  423. For C<process> events, this contains the process instructions (always one
  424. token).
  425. This passes C<undef> for C<text> events.
  426. =item C<tokenpos>
  427. Tokenpos causes a reference to an array of token positions to be
  428. passed. For each string that appears in C<tokens>, this array
  429. contains two numbers. The first number is the offset of the start of
  430. the token in the original C<text> and the second number is the length
  431. of the token.
  432. Boolean attributes in a C<start> event will have (0,0) for the
  433. attribute value offset and length.
  434. This passes undef if there are no tokens in the event (e.g., C<text>)
  435. and for artifical C<end> events triggered by empty element tags.
  436. If you are using these offsets and lengths to modify C<text>, you
  437. should either work from right to left, or be very careful to calculate
  438. the changes to the offsets.
  439. =item C<token0>
  440. Token0 causes the original text of the first token string to be
  441. passed. This should always be the same as $tokens->[0].
  442. For C<declaration> events, this is the declaration type.
  443. For C<start> and C<end> events, this is the tag name.
  444. For C<process> and non-strict C<comment> events, this is everything
  445. inside the tag.
  446. This passes undef if there are no tokens in the event.
  447. =item C<tagname>
  448. This is the element name (or I<generic identifier> in SGML jargon) for
  449. start and end tags. Since HTML is case insensitive this name is
  450. forced to lower case to ease string matching.
  451. Since XML is case sensitive, the tagname case is not
  452. changed when C<xml_mode> is enabled.
  453. The declaration type of declaration elements is also passed as a tagname,
  454. even if that is a bit strange.
  455. In fact, in the current implementation tagname is
  456. identical to C<token0> except that the name may be forced to lower case.
  457. =item C<tag>
  458. Same as C<tagname>, but prefixed with "/" if it belongs to an C<end>
  459. event and "!" for a declaration. The C<tag> does not have any prefix
  460. for C<start> events, and is in this case identical to C<tagname>.
  461. =item C<attr>
  462. Attr causes a reference to a hash of attribute name/value pairs to be
  463. passed.
  464. Boolean attributes' values are either the value set by
  465. $p->boolean_attribute_value or the attribute name if no value has been
  466. set by $p->boolean_attribute_value.
  467. This passes undef except for C<start> events.
  468. Unless C<xml_mode> is enabled, the attribute names are forced to
  469. lower case.
  470. General entities are decoded in the attribute values and
  471. one layer of matching quotes enclosing the attribute values are removed.
  472. =item C<attrseq>
  473. Attrseq causes a reference to an array of attribute names to be
  474. passed. This can be useful if you want to walk the C<attr> hash in
  475. the original sequence.
  476. This passes undef except for C<start> events.
  477. Unless C<xml_mode> is enabled, the attribute names are forced to lower
  478. case.
  479. =item C<@attr>
  480. Basically same as C<attr>, but keys and values are passed as
  481. individual arguments and the original sequence of the attributes is
  482. kept. The parameters passed will be the same as the @attr calculated
  483. here:
  484. @attr = map { $_ => $attr->{$_} } @$attrseq;
  485. assuming $attr and $attrseq here are the hash and array passed as the
  486. result of C<attr> and C<attrseq> argspecs.
  487. This pass no values for events besides C<start>.
  488. =item C<text>
  489. Text causes the source text (including markup element delimiters) to be
  490. passed.
  491. =item C<dtext>
  492. Dtext causes the decoded text to be passed. General entities are
  493. automatically decoded unless the event was inside a CDATA section or
  494. was between literal start and end tags (C<script>, C<style>, C<xmp>,
  495. and C<plaintext>).
  496. The Unicode character set is assumed for entity decoding. With perl
  497. version < 5.7.1 only the Latin1 range is supported, and entities for
  498. characters outside the 0..255 range is left unchanged.
  499. This passes undef except for C<text> events.
  500. =item C<is_cdata>
  501. Is_cdata causes a TRUE value to be passed if the event is inside a CDATA
  502. section or is between literal start and end tags (C<script>,
  503. C<style>, C<xmp>, and C<plaintext>).
  504. When the flag is FALSE for a text event, then you should normally
  505. either use C<dtext> or decode the entities yourself before the text is
  506. processed further.
  507. =item C<skipped_text>
  508. Skipped_text returns the concatenated text of all the events that has
  509. been skipped since the last time an event was reported. Events might
  510. be skipped because no handler is registered for them or because some
  511. filter applies. Skipped text also include marked section markup,
  512. since there is no events that can catch them.
  513. If an C<"">-handler is registered for an event, then the text for this
  514. event is not included in C<skipped_text>. Skipped text both before
  515. and after the C<"">-event is included in the next reported
  516. C<skipped_text>.
  517. =item C<offset>
  518. Offset causes the byte position in the HTML document of the start of
  519. the event to be passed. The first byte in the document is 0.
  520. =item C<length>
  521. Length causes the number of bytes of the source text of the event to
  522. be passed.
  523. =item C<offset_end>
  524. Offset_end causes the byte position in the HTML document of the end of
  525. the event to be passed. This is the same as C<offset> + C<length>.
  526. =item C<event>
  527. Event causes the event name to be passed.
  528. The event name is one of C<text>, C<start>, C<end>, C<declaration>,
  529. C<comment>, C<process>, C<start_document>, C<end_document> or C<default>.
  530. =item C<line>
  531. Line causes the line number of the start of the event to be passed.
  532. The first line in the document is 1. Line counting doesn't start
  533. until at least one handler requests this value to be reported.
  534. =item C<column>
  535. Column causes the column number of the start of the event to be passed.
  536. The first column on a line is 0.
  537. =item C<'...'>
  538. A literal string of 0 to 255 characters enclosed
  539. in single (') or double (") quotes is passed as entered.
  540. =item C<undef>
  541. Pass an undefined value. Useful as padding where the same handler
  542. routine is registered for multiple events.
  543. =back
  544. The whole argspec string can be wrapped up in C<'@{...}'> to signal
  545. that resulting event array should be flatten. This only makes a
  546. difference if an array reference is used as the handler target.
  547. Consider this example:
  548. $p->handler(text => [], 'text');
  549. $p->handler(text => [], '@{text}']);
  550. With two text events; C<"foo">, C<"bar">; then the first one will end
  551. up with [["foo"], ["bar"]] and the second one with ["foo", "bar"] in
  552. the handler target array.
  553. =head2 Events
  554. Handlers for the following events can be registered:
  555. =over
  556. =item C<text>
  557. This event is triggered when plain text (characters) is recognized.
  558. The text may contain multiple lines. A sequence of text may be broken
  559. between several text events unless $p->unbroken_text is enabled.
  560. The parser will make sure that it does not break a word or a sequence
  561. of whitespace between two text events.
  562. =item C<start>
  563. This event is triggered when a start tag is recognized.
  564. Example:
  565. <A HREF="http://www.perl.com/">
  566. =item C<end>
  567. This event is triggered when an end tag is recognized.
  568. Example:
  569. </A>
  570. =item C<declaration>
  571. This event is triggered when a I<markup declaration> is recognized.
  572. For typical HTML documents, the only declaration you are
  573. likely to find is <!DOCTYPE ...>.
  574. Example:
  575. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  576. "http://www.w3.org/TR/html40/strict.dtd">
  577. DTDs inside <!DOCTYPE ...> will confuse HTML::Parser.
  578. =item C<comment>
  579. This event is triggered when a markup comment is recognized.
  580. Example:
  581. <!-- This is a comment -- -- So is this -->
  582. =item C<process>
  583. This event is triggered when a processing instructions markup is
  584. recognized.
  585. The format and content of processing instructions is system and
  586. application dependent.
  587. Examples:
  588. <? HTML processing instructions >
  589. <? XML processing instructions ?>
  590. =item C<start_document>
  591. This event is triggered before any other events for a new document. A
  592. handler for it can be used to initialize stuff. There is no document
  593. text associated with this event.
  594. =item C<end_document>
  595. This event is triggered when $p->eof called and after any remaining
  596. text is flushed. There is no document text associated with this event.
  597. =item C<default>
  598. This event is triggered for events that do not have a specific
  599. handler. You can set up a handler for this event to catch stuff you
  600. did not want to catch explicitly.
  601. =back
  602. =head1 VERSION 2 COMPATIBILITY
  603. When an C<HTML::Parser> object is constructed with no arguments, a set
  604. of handlers is automatically provided that is compatible with the old
  605. HTML::Parser version 2 callback methods.
  606. This is equivalent to the following method calls:
  607. $p->handler(start => "start", "self, tagname, attr, attrseq, text");
  608. $p->handler(end => "end", "self, tagname, text");
  609. $p->handler(text => "text", "self, text, is_cdata");
  610. $p->handler(process => "process", "self, token0, text");
  611. $p->handler(comment =>
  612. sub {
  613. my($self, $tokens) = @_;
  614. for (@$tokens) {$self->comment($_);}},
  615. "self, tokens");
  616. $p->handler(declaration =>
  617. sub {
  618. my $self = shift;
  619. $self->declaration(substr($_[0], 2, -1));},
  620. "self, text");
  621. Setup of these handlers can also be requested with the "api_version =>
  622. 2" constructor option.
  623. =head1 SUBCLASSING
  624. The C<HTML::Parser> class is subclassable. Parser objects are plain
  625. hashes and C<HTML::Parser> reserves only hash keys that start with
  626. "_hparser". The parser state can be set up by invoking the init()
  627. method which takes the same arguments as new().
  628. =head1 EXAMPLES
  629. The first simple example shows how you might strip out comments from
  630. an HTML document. We achieve this by setting up a comment handler that
  631. does nothing and a default handler that will print out anything else:
  632. use HTML::Parser;
  633. HTML::Parser->new(default_h => [sub { print shift }, 'text'],
  634. comment_h => [""],
  635. )->parse_file(shift || die) || die $!;
  636. An alternative implementation is:
  637. use HTML::Parser;
  638. HTML::Parser->new(end_document_h => [sub { print shift },
  639. 'skipped_text'],
  640. comment_h => [""],
  641. )->parse_file(shift || die) || die $!;
  642. This will in most cases be much more efficient since only a sigle
  643. callback will be made.
  644. The next example prints out the text that is inside the <title>
  645. element of an HTML document. Here we start by setting up a start
  646. handler. When it sees the title start tag it enables a text handler
  647. that prints any text found and an end handler that will terminate
  648. parsing as soon as the title end tag is seen:
  649. use HTML::Parser ();
  650. sub start_handler
  651. {
  652. return if shift ne "title";
  653. my $self = shift;
  654. $self->handler(text => sub { print shift }, "dtext");
  655. $self->handler(end => sub { shift->eof if shift eq "title"; },
  656. "tagname,self");
  657. }
  658. my $p = HTML::Parser->new(api_version => 3);
  659. $p->handler( start => \&start_handler, "tagname,self");
  660. $p->parse_file(shift || die) || die $!;
  661. print "\n";
  662. More examples are found in the "eg/" directory of the C<HTML-Parser>
  663. distribution; the program C<hrefsub> shows how you can edit all links
  664. found in a document and C<htextsub> how to edid the text only; the
  665. program C<hstrip> shows how you can strip out certain tags/elements
  666. and/or attributes; and the program C<htext> show how to obtain the
  667. plain text, but not any script/style content.
  668. =head1 BUGS
  669. The <style> and <script> sections do not end with the first "</", but
  670. need the complete corresponding end tag.
  671. When the I<strict_comment> option is enabled, we still recognize
  672. comments where there is something other than whitespace between even
  673. and odd "--" markers.
  674. Once $p->boolean_attribute_value has been set, there is no way to
  675. restore the default behaviour.
  676. There is currently no way to get both quote characters
  677. into the same literal argspec.
  678. Empty tags, e.g. "<>" and "</>", are not recognized. SGML allows them
  679. to repeat the previous start tag or close the previous start tag
  680. respecitvely.
  681. NET tags, e.g. "code/.../" are not recognized. This is an SGML
  682. shorthand for "<code>...</code>".
  683. Unclosed start or end tags, e.g. "<tt<b>...</b</tt>" are not
  684. recognized.
  685. =head1 DIAGNOSTICS
  686. The following messages may be produced by HTML::Parser. The notation
  687. in this listing is the same as used in L<perldiag>:
  688. =over
  689. =item Not a reference to a hash
  690. (F) The object blessed into or subclassed from HTML::Parser is not a
  691. hash as required by the HTML::Parser methods.
  692. =item Bad signature in parser state object at %p
  693. (F) The _hparser_xs_state element does not refer to a valid state structure.
  694. Something must have changed the internal value
  695. stored in this hash element, or the memory has been overwritten.
  696. =item _hparser_xs_state element is not a reference
  697. (F) The _hparser_xs_state element has been destroyed.
  698. =item Can't find '_hparser_xs_state' element in HTML::Parser hash
  699. (F) The _hparser_xs_state element is missing from the parser hash.
  700. It was either deleted, or not created when the object was created.
  701. =item API version %s not supported by HTML::Parser %s
  702. (F) The constructor option 'api_version' with an argument greater than
  703. or equal to 4 is reserved for future extentions.
  704. =item Bad constructor option '%s'
  705. (F) An unknown constructor option key was passed to the new() or
  706. init() methods.
  707. =item Parse loop not allowed
  708. (F) A handler invoked the parse() or parse_file() method.
  709. This is not permitted.
  710. =item marked sections not supported
  711. (F) The $p->marked_sections() method was invoked in a HTML::Parser
  712. module that was compiled without support for marked sections.
  713. =item Unknown boolean attribute (%d)
  714. (F) Something is wrong with the internal logic that set up aliases for
  715. boolean attributes.
  716. =item Only code or array references allowed as handler
  717. (F) The second argument for $p->handler must be either a subroutine
  718. reference, then name of a subroutine or method, or a reference to an
  719. array.
  720. =item No handler for %s events
  721. (F) The first argument to $p->handler must be a valid event name; i.e. one
  722. of "start", "end", "text", "process", "declaration" or "comment".
  723. =item Unrecognized identifier %s in argspec
  724. (F) The identifier is not a known argspec name.
  725. Use one of the names mentioned in the argspec section above.
  726. =item Literal string is longer than 255 chars in argspec
  727. (F) The current implementation limits the length of literals in
  728. an argspec to 255 characters. Make the literal shorter.
  729. =item Backslash reserved for literal string in argspec
  730. (F) The backslash character "\" is not allowed in argspec literals.
  731. It is reserved to permit quoting inside a literal in a later version.
  732. =item Unterminated literal string in argspec
  733. (F) The terminating quote character for a literal was not found.
  734. =item Bad argspec (%s)
  735. (F) Only identifier names, literals, spaces and commas
  736. are allowed in argspecs.
  737. =item Missing comma separator in argspec
  738. (F) Identifiers in an argspec must be separated with ",".
  739. =back
  740. =head1 SEE ALSO
  741. L<HTML::Entities>, L<HTML::PullParser>, L<HTML::TokeParser>, L<HTML::HeadParser>,
  742. L<HTML::LinkExtor>, L<HTML::Form>
  743. L<HTML::TreeBuilder> (part of the I<HTML-Tree> distribution)
  744. http://www.w3.org/TR/REC-html40
  745. More information about marked sections and processing instructions may
  746. be found at C<http://www.sgml.u-net.com/book/sgml-8.htm>.
  747. =head1 COPYRIGHT
  748. Copyright 1996-2001 Gisle Aas. All rights reserved.
  749. Copyright 1999-2000 Michael A. Chase. All rights reserved.
  750. This library is free software; you can redistribute it and/or
  751. modify it under the same terms as Perl itself.
  752. =cut