asda?‰PNG  IHDR ? f ??C1 sRGB ??é gAMA ±? üa pHYs ? ??o¨d GIDATx^íüL”÷e÷Y?a?("Bh?_ò???¢§?q5k?*:t0A-o??¥]VkJ¢M??f?±8\k2íll£1]q?ù???T PKJe[He LinkExtor.pmnu[package HTML::LinkExtor; require HTML::Parser; @ISA = qw(HTML::Parser); $VERSION = "3.69"; =head1 NAME HTML::LinkExtor - Extract links from an HTML document =head1 SYNOPSIS require HTML::LinkExtor; $p = HTML::LinkExtor->new(\&cb, "http://www.perl.org/"); sub cb { my($tag, %links) = @_; print "$tag @{[%links]}\n"; } $p->parse_file("index.html"); =head1 DESCRIPTION I is an HTML parser that extracts links from an HTML document. The I is a subclass of I. This means that the document should be given to the parser by calling the $p->parse() or $p->parse_file() methods. =cut use strict; use HTML::Tagset (); # legacy (some applications grabs this hash directly) use vars qw(%LINK_ELEMENT); *LINK_ELEMENT = \%HTML::Tagset::linkElements; =over 4 =item $p = HTML::LinkExtor->new =item $p = HTML::LinkExtor->new( $callback ) =item $p = HTML::LinkExtor->new( $callback, $base ) The constructor takes two optional arguments. The first is a reference to a callback routine. It will be called as links are found. If a callback is not provided, then links are just accumulated internally and can be retrieved by calling the $p->links() method. The $base argument is an optional base URL used to absolutize all URLs found. You need to have the I module installed if you provide $base. The callback is called with the lowercase tag name as first argument, and then all link attributes as separate key/value pairs. All non-link attributes are removed. =cut sub new { my($class, $cb, $base) = @_; my $self = $class->SUPER::new( start_h => ["_start_tag", "self,tagname,attr"], report_tags => [keys %HTML::Tagset::linkElements], ); $self->{extractlink_cb} = $cb; if ($base) { require URI; $self->{extractlink_base} = URI->new($base); } $self; } sub _start_tag { my($self, $tag, $attr) = @_; my $base = $self->{extractlink_base}; my $links = $HTML::Tagset::linkElements{$tag}; $links = [$links] unless ref $links; my @links; my $a; for $a (@$links) { next unless exists $attr->{$a}; (my $link = $attr->{$a}) =~ s/^\s+//; $link =~ s/\s+$//; # HTML5 push(@links, $a, $base ? URI->new($link, $base)->abs($base) : $link); } return unless @links; $self->_found_link($tag, @links); } sub _found_link { my $self = shift; my $cb = $self->{extractlink_cb}; if ($cb) { &$cb(@_); } else { push(@{$self->{'links'}}, [@_]); } } =item $p->links Returns a list of all links found in the document. The returned values will be anonymous arrays with the following elements: [$tag, $attr => $url1, $attr2 => $url2,...] The $p->links method will also truncate the internal link list. This means that if the method is called twice without any parsing between them the second call will return an empty list. Also note that $p->links will always be empty if a callback routine was provided when the I was created. =cut sub links { my $self = shift; exists($self->{'links'}) ? @{delete $self->{'links'}} : (); } # We override the parse_file() method so that we can clear the links # before we start a new file. sub parse_file { my $self = shift; delete $self->{'links'}; $self->SUPER::parse_file(@_); } =back =head1 EXAMPLE This is an example showing how you can extract links from a document received using LWP: use LWP::UserAgent; use HTML::LinkExtor; use URI::URL; $url = "http://www.perl.org/"; # for instance $ua = LWP::UserAgent->new; # Set up a callback that collect image links my @imgs = (); sub callback { my($tag, %attr) = @_; return if $tag ne 'img'; # we only look closer at push(@imgs, values %attr); } # Make the parser. Unfortunately, we don't know the base yet # (it might be different from $url) $p = HTML::LinkExtor->new(\&callback); # Request document and parse it as it arrives $res = $ua->request(HTTP::Request->new(GET => $url), sub {$p->parse($_[0])}); # Expand all image URLs to absolute ones my $base = $res->base; @imgs = map { $_ = url($_, $base)->abs; } @imgs; # Print them out print join("\n", @imgs), "\n"; =head1 SEE ALSO L, L, L, L =head1 COPYRIGHT Copyright 1996-2001 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PKJe[Ӳ:: Entities.pmnu[package HTML::Entities; =encoding utf8 =head1 NAME HTML::Entities - Encode or decode strings with HTML entities =head1 SYNOPSIS use HTML::Entities; $a = "Våre norske tegn bør æres"; decode_entities($a); encode_entities($a, "\200-\377"); For example, this: $input = "vis-à-vis Beyoncé's naïve\npapier-mâché résumé"; print encode_entities($input), "\n" Prints this out: vis-à-vis Beyoncé's naïve papier-mâché résumé =head1 DESCRIPTION This module deals with encoding and decoding of strings with HTML character entities. The module provides the following functions: =over 4 =item decode_entities( $string, ... ) This routine replaces HTML entities found in the $string with the corresponding Unicode character. Unrecognized entities are left alone. If multiple strings are provided as argument they are each decoded separately and the same number of strings are returned. If called in void context the arguments are decoded in-place. This routine is exported by default. =item _decode_entities( $string, \%entity2char ) =item _decode_entities( $string, \%entity2char, $expand_prefix ) This will in-place replace HTML entities in $string. The %entity2char hash must be provided. Named entities not found in the %entity2char hash are left alone. Numeric entities are expanded unless their value overflow. The keys in %entity2char are the entity names to be expanded and their values are what they should expand into. The values do not have to be single character strings. If a key has ";" as suffix, then occurrences in $string are only expanded if properly terminated with ";". Entities without ";" will be expanded regardless of how they are terminated for compatibility with how common browsers treat entities in the Latin-1 range. If $expand_prefix is TRUE then entities without trailing ";" in %entity2char will even be expanded as a prefix of a longer unrecognized name. The longest matching name in %entity2char will be used. This is mainly present for compatibility with an MSIE misfeature. $string = "foo bar"; _decode_entities($string, { nb => "@", nbsp => "\xA0" }, 1); print $string; # will print "foo bar" This routine is exported by default. =item encode_entities( $string ) =item encode_entities( $string, $unsafe_chars ) This routine replaces unsafe characters in $string with their entity representation. A second argument can be given to specify which characters to consider unsafe. The unsafe characters is specified using the regular expression character class syntax (what you find within brackets in regular expressions). The default set of characters to encode are control chars, high-bit chars, and the C<< < >>, C<< & >>, C<< > >>, C<< ' >> and C<< " >> characters. But this, for example, would encode I the C<< < >>, C<< & >>, C<< > >>, and C<< " >> characters: $encoded = encode_entities($input, '<>&"'); and this would only encode non-plain ascii: $encoded = encode_entities($input, '^\n\x20-\x25\x27-\x7e'); This routine is exported by default. =item encode_entities_numeric( $string ) =item encode_entities_numeric( $string, $unsafe_chars ) This routine works just like encode_entities, except that the replacement entities are always C<&#xI;> and never C<&I;>. For example, C returns "rôle", but C returns "rôle". This routine is I exported by default. But you can always export it with C or even C =back All these routines modify the string passed as the first argument, if called in a void context. In scalar and array contexts, the encoded or decoded string is returned (without changing the input string). If you prefer not to import these routines into your namespace, you can call them as: use HTML::Entities (); $decoded = HTML::Entities::decode($a); $encoded = HTML::Entities::encode($a); $encoded = HTML::Entities::encode_numeric($a); The module can also export the %char2entity and the %entity2char hashes, which contain the mapping from all characters to the corresponding entities (and vice versa, respectively). =head1 COPYRIGHT Copyright 1995-2006 Gisle Aas. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut use strict; use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION); use vars qw(%entity2char %char2entity); require 5.004; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(encode_entities decode_entities _decode_entities); @EXPORT_OK = qw(%entity2char %char2entity encode_entities_numeric); $VERSION = "3.69"; sub Version { $VERSION; } require HTML::Parser; # for fast XS implemented decode_entities %entity2char = ( # Some normal chars that have special meaning in SGML context amp => '&', # ampersand 'gt' => '>', # greater than 'lt' => '<', # less than quot => '"', # double quote apos => "'", # single quote # PUBLIC ISO 8879-1986//ENTITIES Added Latin 1//EN//HTML AElig => chr(198), # capital AE diphthong (ligature) Aacute => chr(193), # capital A, acute accent Acirc => chr(194), # capital A, circumflex accent Agrave => chr(192), # capital A, grave accent Aring => chr(197), # capital A, ring Atilde => chr(195), # capital A, tilde Auml => chr(196), # capital A, dieresis or umlaut mark Ccedil => chr(199), # capital C, cedilla ETH => chr(208), # capital Eth, Icelandic Eacute => chr(201), # capital E, acute accent Ecirc => chr(202), # capital E, circumflex accent Egrave => chr(200), # capital E, grave accent Euml => chr(203), # capital E, dieresis or umlaut mark Iacute => chr(205), # capital I, acute accent Icirc => chr(206), # capital I, circumflex accent Igrave => chr(204), # capital I, grave accent Iuml => chr(207), # capital I, dieresis or umlaut mark Ntilde => chr(209), # capital N, tilde Oacute => chr(211), # capital O, acute accent Ocirc => chr(212), # capital O, circumflex accent Ograve => chr(210), # capital O, grave accent Oslash => chr(216), # capital O, slash Otilde => chr(213), # capital O, tilde Ouml => chr(214), # capital O, dieresis or umlaut mark THORN => chr(222), # capital THORN, Icelandic Uacute => chr(218), # capital U, acute accent Ucirc => chr(219), # capital U, circumflex accent Ugrave => chr(217), # capital U, grave accent Uuml => chr(220), # capital U, dieresis or umlaut mark Yacute => chr(221), # capital Y, acute accent aacute => chr(225), # small a, acute accent acirc => chr(226), # small a, circumflex accent aelig => chr(230), # small ae diphthong (ligature) agrave => chr(224), # small a, grave accent aring => chr(229), # small a, ring atilde => chr(227), # small a, tilde auml => chr(228), # small a, dieresis or umlaut mark ccedil => chr(231), # small c, cedilla eacute => chr(233), # small e, acute accent ecirc => chr(234), # small e, circumflex accent egrave => chr(232), # small e, grave accent eth => chr(240), # small eth, Icelandic euml => chr(235), # small e, dieresis or umlaut mark iacute => chr(237), # small i, acute accent icirc => chr(238), # small i, circumflex accent igrave => chr(236), # small i, grave accent iuml => chr(239), # small i, dieresis or umlaut mark ntilde => chr(241), # small n, tilde oacute => chr(243), # small o, acute accent ocirc => chr(244), # small o, circumflex accent ograve => chr(242), # small o, grave accent oslash => chr(248), # small o, slash otilde => chr(245), # small o, tilde ouml => chr(246), # small o, dieresis or umlaut mark szlig => chr(223), # small sharp s, German (sz ligature) thorn => chr(254), # small thorn, Icelandic uacute => chr(250), # small u, acute accent ucirc => chr(251), # small u, circumflex accent ugrave => chr(249), # small u, grave accent uuml => chr(252), # small u, dieresis or umlaut mark yacute => chr(253), # small y, acute accent yuml => chr(255), # small y, dieresis or umlaut mark # Some extra Latin 1 chars that are listed in the HTML3.2 draft (21-May-96) copy => chr(169), # copyright sign reg => chr(174), # registered sign nbsp => chr(160), # non breaking space # Additional ISO-8859/1 entities listed in rfc1866 (section 14) iexcl => chr(161), cent => chr(162), pound => chr(163), curren => chr(164), yen => chr(165), brvbar => chr(166), sect => chr(167), uml => chr(168), ordf => chr(170), laquo => chr(171), 'not' => chr(172), # not is a keyword in perl shy => chr(173), macr => chr(175), deg => chr(176), plusmn => chr(177), sup1 => chr(185), sup2 => chr(178), sup3 => chr(179), acute => chr(180), micro => chr(181), para => chr(182), middot => chr(183), cedil => chr(184), ordm => chr(186), raquo => chr(187), frac14 => chr(188), frac12 => chr(189), frac34 => chr(190), iquest => chr(191), 'times' => chr(215), # times is a keyword in perl divide => chr(247), ( $] > 5.007 ? ( 'OElig;' => chr(338), 'oelig;' => chr(339), 'Scaron;' => chr(352), 'scaron;' => chr(353), 'Yuml;' => chr(376), 'fnof;' => chr(402), 'circ;' => chr(710), 'tilde;' => chr(732), 'Alpha;' => chr(913), 'Beta;' => chr(914), 'Gamma;' => chr(915), 'Delta;' => chr(916), 'Epsilon;' => chr(917), 'Zeta;' => chr(918), 'Eta;' => chr(919), 'Theta;' => chr(920), 'Iota;' => chr(921), 'Kappa;' => chr(922), 'Lambda;' => chr(923), 'Mu;' => chr(924), 'Nu;' => chr(925), 'Xi;' => chr(926), 'Omicron;' => chr(927), 'Pi;' => chr(928), 'Rho;' => chr(929), 'Sigma;' => chr(931), 'Tau;' => chr(932), 'Upsilon;' => chr(933), 'Phi;' => chr(934), 'Chi;' => chr(935), 'Psi;' => chr(936), 'Omega;' => chr(937), 'alpha;' => chr(945), 'beta;' => chr(946), 'gamma;' => chr(947), 'delta;' => chr(948), 'epsilon;' => chr(949), 'zeta;' => chr(950), 'eta;' => chr(951), 'theta;' => chr(952), 'iota;' => chr(953), 'kappa;' => chr(954), 'lambda;' => chr(955), 'mu;' => chr(956), 'nu;' => chr(957), 'xi;' => chr(958), 'omicron;' => chr(959), 'pi;' => chr(960), 'rho;' => chr(961), 'sigmaf;' => chr(962), 'sigma;' => chr(963), 'tau;' => chr(964), 'upsilon;' => chr(965), 'phi;' => chr(966), 'chi;' => chr(967), 'psi;' => chr(968), 'omega;' => chr(969), 'thetasym;' => chr(977), 'upsih;' => chr(978), 'piv;' => chr(982), 'ensp;' => chr(8194), 'emsp;' => chr(8195), 'thinsp;' => chr(8201), 'zwnj;' => chr(8204), 'zwj;' => chr(8205), 'lrm;' => chr(8206), 'rlm;' => chr(8207), 'ndash;' => chr(8211), 'mdash;' => chr(8212), 'lsquo;' => chr(8216), 'rsquo;' => chr(8217), 'sbquo;' => chr(8218), 'ldquo;' => chr(8220), 'rdquo;' => chr(8221), 'bdquo;' => chr(8222), 'dagger;' => chr(8224), 'Dagger;' => chr(8225), 'bull;' => chr(8226), 'hellip;' => chr(8230), 'permil;' => chr(8240), 'prime;' => chr(8242), 'Prime;' => chr(8243), 'lsaquo;' => chr(8249), 'rsaquo;' => chr(8250), 'oline;' => chr(8254), 'frasl;' => chr(8260), 'euro;' => chr(8364), 'image;' => chr(8465), 'weierp;' => chr(8472), 'real;' => chr(8476), 'trade;' => chr(8482), 'alefsym;' => chr(8501), 'larr;' => chr(8592), 'uarr;' => chr(8593), 'rarr;' => chr(8594), 'darr;' => chr(8595), 'harr;' => chr(8596), 'crarr;' => chr(8629), 'lArr;' => chr(8656), 'uArr;' => chr(8657), 'rArr;' => chr(8658), 'dArr;' => chr(8659), 'hArr;' => chr(8660), 'forall;' => chr(8704), 'part;' => chr(8706), 'exist;' => chr(8707), 'empty;' => chr(8709), 'nabla;' => chr(8711), 'isin;' => chr(8712), 'notin;' => chr(8713), 'ni;' => chr(8715), 'prod;' => chr(8719), 'sum;' => chr(8721), 'minus;' => chr(8722), 'lowast;' => chr(8727), 'radic;' => chr(8730), 'prop;' => chr(8733), 'infin;' => chr(8734), 'ang;' => chr(8736), 'and;' => chr(8743), 'or;' => chr(8744), 'cap;' => chr(8745), 'cup;' => chr(8746), 'int;' => chr(8747), 'there4;' => chr(8756), 'sim;' => chr(8764), 'cong;' => chr(8773), 'asymp;' => chr(8776), 'ne;' => chr(8800), 'equiv;' => chr(8801), 'le;' => chr(8804), 'ge;' => chr(8805), 'sub;' => chr(8834), 'sup;' => chr(8835), 'nsub;' => chr(8836), 'sube;' => chr(8838), 'supe;' => chr(8839), 'oplus;' => chr(8853), 'otimes;' => chr(8855), 'perp;' => chr(8869), 'sdot;' => chr(8901), 'lceil;' => chr(8968), 'rceil;' => chr(8969), 'lfloor;' => chr(8970), 'rfloor;' => chr(8971), 'lang;' => chr(9001), 'rang;' => chr(9002), 'loz;' => chr(9674), 'spades;' => chr(9824), 'clubs;' => chr(9827), 'hearts;' => chr(9829), 'diams;' => chr(9830), ) : ()) ); # Make the opposite mapping while (my($entity, $char) = each(%entity2char)) { $entity =~ s/;\z//; $char2entity{$char} = "&$entity;"; } delete $char2entity{"'"}; # only one-way decoding # Fill in missing entities for (0 .. 255) { next if exists $char2entity{chr($_)}; $char2entity{chr($_)} = "&#$_;"; } my %subst; # compiled encoding regexps sub encode_entities { return undef unless defined $_[0]; my $ref; if (defined wantarray) { my $x = $_[0]; $ref = \$x; # copy } else { $ref = \$_[0]; # modify in-place } if (defined $_[1] and length $_[1]) { unless (exists $subst{$_[1]}) { # Because we can't compile regex we fake it with a cached sub my $chars = $_[1]; $chars =~ s,(?', ''' and '"' $$ref =~ s/([^\n\r\t !\#\$%\(-;=?-~])/$char2entity{$1} || num_entity($1)/ge; } $$ref; } sub encode_entities_numeric { local %char2entity; return &encode_entities; # a goto &encode_entities wouldn't work } sub num_entity { sprintf "&#x%X;", ord($_[0]); } # Set up aliases *encode = \&encode_entities; *encode_numeric = \&encode_entities_numeric; *encode_numerically = \&encode_entities_numeric; *decode = \&decode_entities; 1; PKJe[fN!N! HeadParser.pmnu[package HTML::HeadParser; =head1 NAME HTML::HeadParser - Parse section of a HTML document =head1 SYNOPSIS require HTML::HeadParser; $p = HTML::HeadParser->new; $p->parse($text) and print "not finished"; $p->header('Title') # to access .... $p->header('Content-Base') # to access $p->header('Foo') # to access $p->header('X-Meta-Author') # to access $p->header('X-Meta-Charset') # to access =head1 DESCRIPTION The C is a specialized (and lightweight) C that will only parse the EHEAD>...E/HEAD> section of an HTML document. The parse() method will return a FALSE value as soon as some EBODY> element or body text are found, and should not be called again after this. Note that the C might get confused if raw undecoded UTF-8 is passed to the parse() method. Make sure the strings are properly decoded before passing them on. The C keeps a reference to a header object, and the parser will update this header object as the various elements of the EHEAD> section of the HTML document are recognized. The following header fields are affected: =over 4 =item Content-Base: The I header is initialized from the Ebase href="..."> element. =item Title: The I header is initialized from the E<lt>title>...E<lt>/title> element. =item Isindex: The I<Isindex> header will be added if there is a E<lt>isindex> element in the E<lt>head>. The header value is initialized from the I<prompt> attribute if it is present. If no I<prompt> attribute is given it will have '?' as the value. =item X-Meta-Foo: All E<lt>meta> elements containing a C<name> attribute will result in headers using the prefix C<X-Meta-> appended with the value of the C<name> attribute as the name of the header, and the value of the C<content> attribute as the pushed header value. E<lt>meta> elements containing a C<http-equiv> attribute will result in headers as in above, but without the C<X-Meta-> prefix in the header name. E<lt>meta> elements containing a C<charset> attribute will result in an C<X-Meta-Charset> header, using the value of the C<charset> attribute as the pushed header value. The ':' character can't be represented in header field names, so if the meta element contains this char it's substituted with '-' before forming the field name. =back =head1 METHODS The following methods (in addition to those provided by the superclass) are available: =over 4 =cut require HTML::Parser; @ISA = qw(HTML::Parser); use HTML::Entities (); use strict; use vars qw($VERSION $DEBUG); #$DEBUG = 1; $VERSION = "3.71"; =item $hp = HTML::HeadParser->new =item $hp = HTML::HeadParser->new( $header ) The object constructor. The optional $header argument should be a reference to an object that implement the header() and push_header() methods as defined by the C<HTTP::Headers> class. Normally it will be of some class that is a or delegates to the C<HTTP::Headers> class. If no $header is given C<HTML::HeadParser> will create an C<HTTP::Headers> object by itself (initially empty). =cut sub new { my($class, $header) = @_; unless ($header) { require HTTP::Headers; $header = HTTP::Headers->new; } my $self = $class->SUPER::new(api_version => 3, start_h => ["start", "self,tagname,attr"], end_h => ["end", "self,tagname"], text_h => ["text", "self,text"], ignore_elements => [qw(script style)], ); $self->{'header'} = $header; $self->{'tag'} = ''; # name of active element that takes textual content $self->{'text'} = ''; # the accumulated text associated with the element $self; } =item $hp->header; Returns a reference to the header object. =item $hp->header( $key ) Returns a header value. It is just a shorter way to write C<$hp-E<gt>header-E<gt>header($key)>. =cut sub header { my $self = shift; return $self->{'header'} unless @_; $self->{'header'}->header(@_); } sub as_string # legacy { my $self = shift; $self->{'header'}->as_string; } sub flush_text # internal { my $self = shift; my $tag = $self->{'tag'}; my $text = $self->{'text'}; $text =~ s/^\s+//; $text =~ s/\s+$//; $text =~ s/\s+/ /g; print "FLUSH $tag => '$text'\n" if $DEBUG; if ($tag eq 'title') { my $decoded; $decoded = utf8::decode($text) if $self->utf8_mode && defined &utf8::decode; HTML::Entities::decode($text); utf8::encode($text) if $decoded; $self->{'header'}->push_header(Title => $text); } $self->{'tag'} = $self->{'text'} = ''; } # This is an quote from the HTML3.2 DTD which shows which elements # that might be present in a <HEAD>...</HEAD>. Also note that the # <HEAD> tags themselves might be missing: # # <!ENTITY % head.content "TITLE & ISINDEX? & BASE? & STYLE? & # SCRIPT* & META* & LINK*"> # # <!ELEMENT HEAD O O (%head.content)> # # From HTML 4.01: # # <!ENTITY % head.misc "SCRIPT|STYLE|META|LINK|OBJECT"> # <!ENTITY % head.content "TITLE & BASE?"> # <!ELEMENT HEAD O O (%head.content;) +(%head.misc;)> # # From HTML 5 as of WD-html5-20090825: # # One or more elements of metadata content, [...] # => base, command, link, meta, noscript, script, style, title sub start { my($self, $tag, $attr) = @_; # $attr is reference to a HASH print "START[$tag]\n" if $DEBUG; $self->flush_text if $self->{'tag'}; if ($tag eq 'meta') { my $key = $attr->{'http-equiv'}; if (!defined($key) || !length($key)) { if ($attr->{name}) { $key = "X-Meta-\u$attr->{name}"; } elsif ($attr->{charset}) { # HTML 5 <meta charset="..."> $key = "X-Meta-Charset"; $self->{header}->push_header($key => $attr->{charset}); return; } else { return; } } $key =~ s/:/-/g; $self->{'header'}->push_header($key => $attr->{content}); } elsif ($tag eq 'base') { return unless exists $attr->{href}; (my $base = $attr->{href}) =~ s/^\s+//; $base =~ s/\s+$//; # HTML5 $self->{'header'}->push_header('Content-Base' => $base); } elsif ($tag eq 'isindex') { # This is a non-standard header. Perhaps we should just ignore # this element $self->{'header'}->push_header(Isindex => $attr->{prompt} || '?'); } elsif ($tag =~ /^(?:title|noscript|object|command)$/) { # Just remember tag. Initialize header when we see the end tag. $self->{'tag'} = $tag; } elsif ($tag eq 'link') { return unless exists $attr->{href}; # <link href="http:..." rel="xxx" rev="xxx" title="xxx"> my $href = delete($attr->{href}); $href =~ s/^\s+//; $href =~ s/\s+$//; # HTML5 my $h_val = "<$href>"; for (sort keys %{$attr}) { next if $_ eq "/"; # XHTML junk $h_val .= qq(; $_="$attr->{$_}"); } $self->{'header'}->push_header(Link => $h_val); } elsif ($tag eq 'head' || $tag eq 'html') { # ignore } else { # stop parsing $self->eof; } } sub end { my($self, $tag) = @_; print "END[$tag]\n" if $DEBUG; $self->flush_text if $self->{'tag'}; $self->eof if $tag eq 'head'; } sub text { my($self, $text) = @_; print "TEXT[$text]\n" if $DEBUG; unless ($self->{first_chunk}) { # drop Unicode BOM if found if ($self->utf8_mode) { $text =~ s/^\xEF\xBB\xBF//; } else { $text =~ s/^\x{FEFF}//; } $self->{first_chunk}++; } my $tag = $self->{tag}; if (!$tag && $text =~ /\S/) { # Normal text means start of body $self->eof; return; } return if $tag ne 'title'; $self->{'text'} .= $text; } BEGIN { *utf8_mode = sub { 1 } unless HTML::Entities::UNICODE_SUPPORT; } 1; __END__ =back =head1 EXAMPLE $h = HTTP::Headers->new; $p = HTML::HeadParser->new($h); $p->parse(<<EOT); <title>Stupid example Normal text starts here. EOT undef $p; print $h->title; # should print "Stupid example" =head1 SEE ALSO L, L The C class is distributed as part of the I package. If you don't have that distribution installed you need to provide the $header argument to the C constructor with your own object that implements the documented protocol. =head1 COPYRIGHT Copyright 1996-2001 Gisle Aas. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PKJe[y y Filter.pmnu[package HTML::Filter; use strict; use vars qw(@ISA $VERSION); require HTML::Parser; @ISA=qw(HTML::Parser); $VERSION = "3.72"; sub declaration { $_[0]->output("") } sub process { $_[0]->output($_[2]) } sub comment { $_[0]->output("") } sub start { $_[0]->output($_[4]) } sub end { $_[0]->output($_[2]) } sub text { $_[0]->output($_[1]) } sub output { print $_[1] } 1; __END__ =head1 NAME HTML::Filter - Filter HTML text through the parser =head1 NOTE B The C now provides the functionally of C much more efficiently with the C handler. =head1 SYNOPSIS require HTML::Filter; $p = HTML::Filter->new->parse_file("index.html"); =head1 DESCRIPTION C is an HTML parser that by default prints the original text of each HTML element (a slow version of cat(1) basically). The callback methods may be overridden to modify the filtering for some HTML elements and you can override output() method which is called to print the HTML text. C is a subclass of C. This means that the document should be given to the parser by calling the $p->parse() or $p->parse_file() methods. =head1 EXAMPLES The first example is a filter that will remove all comments from an HTML file. This is achieved by simply overriding the comment method to do nothing. package CommentStripper; require HTML::Filter; @ISA=qw(HTML::Filter); sub comment { } # ignore comments The second example shows a filter that will remove any ETABLE>s found in the HTML file. We specialize the start() and end() methods to count table tags and then make output not happen when inside a table. package TableStripper; require HTML::Filter; @ISA=qw(HTML::Filter); sub start { my $self = shift; $self->{table_seen}++ if $_[0] eq "table"; $self->SUPER::start(@_); } sub end { my $self = shift; $self->SUPER::end(@_); $self->{table_seen}-- if $_[0] eq "table"; } sub output { my $self = shift; unless ($self->{table_seen}) { $self->SUPER::output(@_); } } If you want to collect the parsed text internally you might want to do something like this: package FilterIntoString; require HTML::Filter; @ISA=qw(HTML::Filter); sub output { push(@{$_[0]->{fhtml}}, $_[1]) } sub filtered_html { join("", @{$_[0]->{fhtml}}) } =head1 SEE ALSO L =head1 COPYRIGHT Copyright 1997-1999 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PKJe[,911 PullParser.pmnu[package HTML::PullParser; require HTML::Parser; @ISA=qw(HTML::Parser); $VERSION = "3.57"; use strict; use Carp (); sub new { my($class, %cnf) = @_; # Construct argspecs for the various events my %argspec; for (qw(start end text declaration comment process default)) { my $tmp = delete $cnf{$_}; next unless defined $tmp; $argspec{$_} = $tmp; } Carp::croak("Info not collected for any events") unless %argspec; my $file = delete $cnf{file}; my $doc = delete $cnf{doc}; Carp::croak("Can't parse from both 'doc' and 'file' at the same time") if defined($file) && defined($doc); Carp::croak("No 'doc' or 'file' given to parse from") unless defined($file) || defined($doc); # Create object $cnf{api_version} = 3; my $self = $class->SUPER::new(%cnf); my $accum = $self->{pullparser_accum} = []; while (my($event, $argspec) = each %argspec) { $self->SUPER::handler($event => $accum, $argspec); } if (defined $doc) { $self->{pullparser_str_ref} = ref($doc) ? $doc : \$doc; $self->{pullparser_str_pos} = 0; } else { if (!ref($file) && ref(\$file) ne "GLOB") { require IO::File; $file = IO::File->new($file, "r") || return; } $self->{pullparser_file} = $file; } $self; } sub handler { Carp::croak("Can't set handlers for HTML::PullParser"); } sub get_token { my $self = shift; while (!@{$self->{pullparser_accum}} && !$self->{pullparser_eof}) { if (my $f = $self->{pullparser_file}) { # must try to parse more from the file my $buf; if (read($f, $buf, 512)) { $self->parse($buf); } else { $self->eof; $self->{pullparser_eof}++; delete $self->{pullparser_file}; } } elsif (my $sref = $self->{pullparser_str_ref}) { # must try to parse more from the scalar my $pos = $self->{pullparser_str_pos}; my $chunk = substr($$sref, $pos, 512); $self->parse($chunk); $pos += length($chunk); if ($pos < length($$sref)) { $self->{pullparser_str_pos} = $pos; } else { $self->eof; $self->{pullparser_eof}++; delete $self->{pullparser_str_ref}; delete $self->{pullparser_str_pos}; } } else { die; } } shift @{$self->{pullparser_accum}}; } sub unget_token { my $self = shift; unshift @{$self->{pullparser_accum}}, @_; $self; } 1; __END__ =head1 NAME HTML::PullParser - Alternative HTML::Parser interface =head1 SYNOPSIS use HTML::PullParser; $p = HTML::PullParser->new(file => "index.html", start => 'event, tagname, @attr', end => 'event, tagname', ignore_elements => [qw(script style)], ) || die "Can't open: $!"; while (my $token = $p->get_token) { #...do something with $token } =head1 DESCRIPTION The HTML::PullParser is an alternative interface to the HTML::Parser class. It basically turns the HTML::Parser inside out. You associate a file (or any IO::Handle object or string) with the parser at construction time and then repeatedly call $parser->get_token to obtain the tags and text found in the parsed document. The following methods are provided: =over 4 =item $p = HTML::PullParser->new( file => $file, %options ) =item $p = HTML::PullParser->new( doc => \$doc, %options ) A C can be made to parse from either a file or a literal document based on whether the C or C option is passed to the parser's constructor. The C passed in can either be a file name or a file handle object. If a file name is passed, and it can't be opened for reading, then the constructor will return an undefined value and $! will tell you why it failed. Otherwise the argument is taken to be some object that the C can read() from when it needs more data. The stream will be read() until EOF, but not closed. A C can be passed plain or as a reference to a scalar. If a reference is passed then the value of this scalar should not be changed before all tokens have been extracted. Next the information to be returned for the different token types must be set up. This is done by simply associating an argspec (as defined in L) with the events you have an interest in. For instance, if you want C tokens to be reported as the string C<'S'> followed by the tagname and the attributes you might pass an C-option like this: $p = HTML::PullParser->new( doc => $document_to_parse, start => '"S", tagname, @attr', end => '"E", tagname', ); At last other C options, like C, and C, can be passed in. Note that you should not use the I_h options to set up parser handlers. That would confuse the inner logic of C. =item $token = $p->get_token This method will return the next I found in the HTML document, or C at the end of the document. The token is returned as an array reference. The content of this array match the argspec set up during C construction. =item $p->unget_token( @tokens ) If you find out you have read too many tokens you can push them back, so that they are returned again the next time $p->get_token is called. =back =head1 EXAMPLES The 'eg/hform' script shows how we might parse the form section of HTML::Documents using HTML::PullParser. =head1 SEE ALSO L, L =head1 COPYRIGHT Copyright 1998-2001 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PKJe[=« Parser.pmnu[package HTML::Parser; use strict; use vars qw($VERSION @ISA); $VERSION = "3.72"; require HTML::Entities; require XSLoader; XSLoader::load('HTML::Parser', $VERSION); sub new { my $class = shift; my $self = bless {}, $class; return $self->init(@_); } sub init { my $self = shift; $self->_alloc_pstate; my %arg = @_; my $api_version = delete $arg{api_version} || (@_ ? 3 : 2); if ($api_version >= 4) { require Carp; Carp::croak("API version $api_version not supported " . "by HTML::Parser $VERSION"); } if ($api_version < 3) { # Set up method callbacks compatible with HTML-Parser-2.xx $self->handler(text => "text", "self,text,is_cdata"); $self->handler(end => "end", "self,tagname,text"); $self->handler(process => "process", "self,token0,text"); $self->handler(start => "start", "self,tagname,attr,attrseq,text"); $self->handler(comment => sub { my($self, $tokens) = @_; for (@$tokens) { $self->comment($_); } }, "self,tokens"); $self->handler(declaration => sub { my $self = shift; $self->declaration(substr($_[0], 2, -1)); }, "self,text"); } if (my $h = delete $arg{handlers}) { $h = {@$h} if ref($h) eq "ARRAY"; while (my($event, $cb) = each %$h) { $self->handler($event => @$cb); } } # In the end we try to assume plain attribute or handler while (my($option, $val) = each %arg) { if ($option =~ /^(\w+)_h$/) { $self->handler($1 => @$val); } elsif ($option =~ /^(text|start|end|process|declaration|comment)$/) { require Carp; Carp::croak("Bad constructor option '$option'"); } else { $self->$option($val); } } return $self; } sub parse_file { my($self, $file) = @_; my $opened; if (!ref($file) && ref(\$file) ne "GLOB") { # Assume $file is a filename local(*F); open(F, "<", $file) || return undef; binmode(F); # should we? good for byte counts $opened++; $file = *F; } my $chunk = ''; while (read($file, $chunk, 512)) { $self->parse($chunk) || last; } close($file) if $opened; $self->eof; } sub netscape_buggy_comment # legacy { my $self = shift; require Carp; Carp::carp("netscape_buggy_comment() is deprecated. " . "Please use the strict_comment() method instead"); my $old = !$self->strict_comment; $self->strict_comment(!shift) if @_; return $old; } # set up method stubs sub text { } *start = \&text; *end = \&text; *comment = \&text; *declaration = \&text; *process = \&text; 1; __END__ =head1 NAME HTML::Parser - HTML parser class =head1 SYNOPSIS use HTML::Parser (); # Create parser object $p = HTML::Parser->new( api_version => 3, start_h => [\&start, "tagname, attr"], end_h => [\&end, "tagname"], marked_sections => 1, ); # Parse document text chunk by chunk $p->parse($chunk1); $p->parse($chunk2); #... $p->eof; # signal end of document # Parse directly from file $p->parse_file("foo.html"); # or open(my $fh, "<:utf8", "foo.html") || die; $p->parse_file($fh); =head1 DESCRIPTION Objects of the C class will recognize markup and separate it from plain text (alias data content) in HTML documents. As different kinds of markup and text are recognized, the corresponding event handlers are invoked. C is not a generic SGML parser. We have tried to make it able to deal with the HTML that is actually "out there", and it normally parses as closely as possible to the way the popular web browsers do it instead of strictly following one of the many HTML specifications from W3C. Where there is disagreement, there is often an option that you can enable to get the official behaviour. The document to be parsed may be supplied in arbitrary chunks. This makes on-the-fly parsing as documents are received from the network possible. If event driven parsing does not feel right for your application, you might want to use C. This is an C subclass that allows a more conventional program structure. =head1 METHODS The following method is used to construct a new C object: =over =item $p = HTML::Parser->new( %options_and_handlers ) This class method creates a new C object and returns it. Key/value argument pairs may be provided to assign event handlers or initialize parser options. The handlers and parser options can also be set or modified later by the method calls described below. If a top level key is in the form "_h" (e.g., "text_h") then it assigns a handler to that event, otherwise it initializes a parser option. The event handler specification value must be an array reference. Multiple handlers may also be assigned with the 'handlers => [%handlers]' option. See examples below. If new() is called without any arguments, it will create a parser that uses callback methods compatible with version 2 of C. See the section on "version 2 compatibility" below for details. The special constructor option 'api_version => 2' can be used to initialize version 2 callbacks while still setting other options and handlers. The 'api_version => 3' option can be used if you don't want to set any options and don't want to fall back to v2 compatible mode. Examples: $p = HTML::Parser->new(api_version => 3, text_h => [ sub {...}, "dtext" ]); This creates a new parser object with a text event handler subroutine that receives the original text with general entities decoded. $p = HTML::Parser->new(api_version => 3, start_h => [ 'my_start', "self,tokens" ]); This creates a new parser object with a start event handler method that receives the $p and the tokens array. $p = HTML::Parser->new(api_version => 3, handlers => { text => [\@array, "event,text"], comment => [\@array, "event,text"], }); This creates a new parser object that stores the event type and the original text in @array for text and comment events. =back The following methods feed the HTML document to the C object: =over =item $p->parse( $string ) Parse $string as the next chunk of the HTML document. Handlers invoked should not attempt to modify the $string in-place until $p->parse returns. If an invoked event handler aborts parsing by calling $p->eof, then $p->parse() will return a FALSE value. Otherwise the return value is a reference to the parser object ($p). =item $p->parse( $code_ref ) If a code reference is passed as the argument to be parsed, then the chunks to be parsed are obtained by invoking this function repeatedly. Parsing continues until the function returns an empty (or undefined) result. When this happens $p->eof is automatically signaled. Parsing will also abort if one of the event handlers calls $p->eof. The effect of this is the same as: while (1) { my $chunk = &$code_ref(); if (!defined($chunk) || !length($chunk)) { $p->eof; return $p; } $p->parse($chunk) || return undef; } But it is more efficient as this loop runs internally in XS code. =item $p->parse_file( $file ) Parse text directly from a file. The $file argument can be a filename, an open file handle, or a reference to an open file handle. If $file contains a filename and the file can't be opened, then the method returns an undefined value and $! tells why it failed. Otherwise the return value is a reference to the parser object. If a file handle is passed as the $file argument, then the file will normally be read until EOF, but not closed. If an invoked event handler aborts parsing by calling $p->eof, then $p->parse_file() may not have read the entire file. On systems with multi-byte line terminators, the values passed for the offset and length argspecs may be too low if parse_file() is called on a file handle that is not in binary mode. If a filename is passed in, then parse_file() will open the file in binary mode. =item $p->eof Signals the end of the HTML document. Calling the $p->eof method outside a handler callback will flush any remaining buffered text (which triggers the C event if there is any remaining text). Calling $p->eof inside a handler will terminate parsing at that point and cause $p->parse to return a FALSE value. This also terminates parsing by $p->parse_file(). After $p->eof has been called, the parse() and parse_file() methods can be invoked to feed new documents with the parser object. The return value from eof() is a reference to the parser object. =back Most parser options are controlled by boolean attributes. Each boolean attribute is enabled by calling the corresponding method with a TRUE argument and disabled with a FALSE argument. The attribute value is left unchanged if no argument is given. The return value from each method is the old attribute value. Methods that can be used to get and/or set parser options are: =over =item $p->attr_encoded =item $p->attr_encoded( $bool ) By default, the C and C<@attr> argspecs will have general entities for attribute values decoded. Enabling this attribute leaves entities alone. =item $p->backquote =item $p->backquote( $bool ) By default, only ' and " are recognized as quote characters around attribute values. MSIE also recognizes backquotes for some reason. Enabling this attribute provides compatibility with this behaviour. =item $p->boolean_attribute_value( $val ) This method sets the value reported for boolean attributes inside HTML start tags. By default, the name of the attribute is also used as its value. This affects the values reported for C and C argspecs. =item $p->case_sensitive =item $p->case_sensitive( $bool ) By default, tagnames and attribute names are down-cased. Enabling this attribute leaves them as found in the HTML source document. =item $p->closing_plaintext =item $p->closing_plaintext( $bool ) By default, "plaintext" element can never be closed. Everything up to the end of the document is parsed in CDATA mode. This historical behaviour is what at least MSIE does. Enabling this attribute makes closing "" tag effective and the parsing process will resume after seeing this tag. This emulates early gecko-based browsers. =item $p->empty_element_tags =item $p->empty_element_tags( $bool ) By default, empty element tags are not recognized as such and the "/" before ">" is just treated like a normal name character (unless C is enabled). Enabling this attribute make C recognize these tags. Empty element tags look like start tags, but end with the character sequence "/>" instead of ">". When recognized by C they cause an artificial end event in addition to the start event. The C for the artificial end event will be empty and the C array will be undefined even though the token array will have one element containing the tag name. =item $p->marked_sections =item $p->marked_sections( $bool ) By default, section markings like are treated like ordinary text. When this attribute is enabled section markings are honoured. There are currently no events associated with the marked section markup, but the text can be returned as C. =item $p->strict_comment =item $p->strict_comment( $bool ) By default, comments are terminated by the first occurrence of "-->". This is the behaviour of most popular browsers (like Mozilla, Opera and MSIE), but it is not correct according to the official HTML standard. Officially, you need an even number of "--" tokens before the closing ">" is recognized and there may not be anything but whitespace between an even and an odd "--". The official behaviour is enabled by enabling this attribute. Enabling of 'strict_comment' also disables recognizing these forms as comments: =item $p->strict_end =item $p->strict_end( $bool ) By default, attributes and other junk are allowed to be present on end tags in a manner that emulates MSIE's behaviour. The official behaviour is enabled with this attribute. If enabled, only whitespace is allowed between the tagname and the final ">". =item $p->strict_names =item $p->strict_names( $bool ) By default, almost anything is allowed in tag and attribute names. This is the behaviour of most popular browsers and allows us to parse some broken tags with invalid attribute values like: [PREV By default, "LIST]" is parsed as a boolean attribute, not as part of the ALT value as was clearly intended. This is also what Mozilla sees. The official behaviour is enabled by enabling this attribute. If enabled, it will cause the tag above to be reported as text since "LIST]" is not a legal attribute name. =item $p->unbroken_text =item $p->unbroken_text( $bool ) By default, blocks of text are given to the text handler as soon as possible (but the parser takes care always to break text at a boundary between whitespace and non-whitespace so single words and entities can always be decoded safely). This might create breaks that make it hard to do transformations on the text. When this attribute is enabled, blocks of text are always reported in one piece. This will delay the text event until the following (non-text) event has been recognized by the parser. Note that the C argspec will give you the offset of the first segment of text and C is the combined length of the segments. Since there might be ignored tags in between, these numbers can't be used to directly index in the original document file. =item $p->utf8_mode =item $p->utf8_mode( $bool ) Enable this option when parsing raw undecoded UTF-8. This tells the parser that the entities expanded for strings reported by C, C<@attr> and C should be expanded as decoded UTF-8 so they end up compatible with the surrounding text. If C is enabled then it is an error to pass strings containing characters with code above 255 to the parse() method, and the parse() method will croak if you try. Example: The Unicode character "\x{2665}" is "\xE2\x99\xA5" when UTF-8 encoded. The character can also be represented by the entity "♥" or "♥". If we feed the parser: $p->parse("\xE2\x99\xA5♥"); then C will be reported as "\xE2\x99\xA5\x{2665}" without C enabled, but as "\xE2\x99\xA5\xE2\x99\xA5" when enabled. The later string is what you want. This option is only available with perl-5.8 or better. =item $p->xml_mode =item $p->xml_mode( $bool ) Enabling this attribute changes the parser to allow some XML constructs. This enables the behaviour controlled by individually by the C, C, C and C attributes and also suppresses special treatment of elements that are parsed as CDATA for HTML. =item $p->xml_pic =item $p->xml_pic( $bool ) By default, I are terminated by ">". When this attribute is enabled, processing instructions are terminated by "?>" instead. =back As markup and text is recognized, handlers are invoked. The following method is used to set up handlers for different events: =over =item $p->handler( event => \&subroutine, $argspec ) =item $p->handler( event => $method_name, $argspec ) =item $p->handler( event => \@accum, $argspec ) =item $p->handler( event => "" ); =item $p->handler( event => undef ); =item $p->handler( event ); This method assigns a subroutine, method, or array to handle an event. Event is one of C, C, C, C, C, C, C, C or C. The C<\&subroutine> is a reference to a subroutine which is called to handle the event. The C<$method_name> is the name of a method of $p which is called to handle the event. The C<@accum> is an array that will hold the event information as sub-arrays. If the second argument is "", the event is ignored. If it is undef, the default handler is invoked for the event. The C<$argspec> is a string that describes the information to be reported for the event. Any requested information that does not apply to a specific event is passed as C. If argspec is omitted, then it is left unchanged. The return value from $p->handler is the old callback routine or a reference to the accumulator array. Any return values from handler callback routines/methods are always ignored. A handler callback can request parsing to be aborted by invoking the $p->eof method. A handler callback is not allowed to invoke the $p->parse() or $p->parse_file() method. An exception will be raised if it tries. Examples: $p->handler(start => "start", 'self, attr, attrseq, text' ); This causes the "start" method of object $p to be called for 'start' events. The callback signature is $p->start(\%attr, \@attr_seq, $text). $p->handler(start => \&start, 'attr, attrseq, text' ); This causes subroutine start() to be called for 'start' events. The callback signature is start(\%attr, \@attr_seq, $text). $p->handler(start => \@accum, '"S", attr, attrseq, text' ); This causes 'start' event information to be saved in @accum. The array elements will be ['S', \%attr, \@attr_seq, $text]. $p->handler(start => ""); This causes 'start' events to be ignored. It also suppresses invocations of any default handler for start events. It is in most cases equivalent to $p->handler(start => sub {}), but is more efficient. It is different from the empty-sub-handler in that C is not reset by it. $p->handler(start => undef); This causes no handler to be associated with start events. If there is a default handler it will be invoked. =back Filters based on tags can be set up to limit the number of events reported. The main bottleneck during parsing is often the huge number of callbacks made from the parser. Applying filters can improve performance significantly. The following methods control filters: =over =item $p->ignore_elements( @tags ) Both the C event and the C event as well as any events that would be reported in between are suppressed. The ignored elements can contain nested occurrences of itself. Example: $p->ignore_elements(qw(script style)); The C