HTML::Parser#
Parse HTML into events: start and end tags, text, comments, declarations, processing instructions.
HTML::Parser reads HTML the way browsers tolerate it - unquoted and unclosed attributes, stray <, comments that end at the first > in a damaged document - and reports what it finds to handlers you register, with exactly the pieces you ask for ('tagname, attr', 'dtext', 'offset, length', …). It parses incrementally: feed the document in chunks as it arrives, then eof. HTML::Entities decodes and encodes character entities, and HTML::TokeParser, HTML::PullParser, HTML::LinkExtor, HTML::HeadParser and HTML::Filter are built on the parser.
use HTML::Parser;
binmode STDOUT, ':utf8';
my $p = HTML::Parser->new(
api_version => 3,
start_h => [sub { print "start $_[0] @{[ %{$_[1]} ]}\n" }, 'tagname, attr'],
text_h => [sub { print "text [$_[0]]\n" if $_[0] =~ /\S/ }, 'dtext'],
);
$p->parse('<p class=x>café & <b>bar</b></p>');
$p->eof;
# start p class x
# text [café & ]
# start b
# text [bar]
This is a native implementation of the XS half of HTML-Parser 3.86 (hparser.c, util.c, Parser.xs, with marked sections enabled as upstream builds them); its HTML/Parser.pm, HTML/Entities.pm and the other modules of the dist are used unchanged.
Differences from upstream#
None in behaviour.
Functions#
Parsing#
parse#
Parse a chunk of the document, or chunks from a code reference until it returns nothing. Returns the parser, or undef when a handler called eof meanwhile.
eof#
End the document: flush what is buffered and report the end. Called from a handler, parsing stops after the current event.
Configuration#
strict_comment#
Get, and with an argument set, one of the boolean options: strict_comment, strict_names, xml_mode, unbroken_text, marked_sections, attr_encoded, case_sensitive, strict_end, closing_plaintext, utf8_mode, empty_element_tags, xml_pic, backquote.
Also available as HTML::Parser::strict_names, HTML::Parser::xml_mode, HTML::Parser::unbroken_text, HTML::Parser::marked_sections, HTML::Parser::attr_encoded, HTML::Parser::case_sensitive, HTML::Parser::strict_end, HTML::Parser::closing_plaintext, HTML::Parser::utf8_mode, HTML::Parser::empty_element_tags, HTML::Parser::xml_pic, HTML::Parser::backquote.
boolean_attribute_value#
Get, and with an argument set, the value a boolean attribute (one written without =value) gets; by default its name.
Handlers#
handler#
Get the handler of an event; with more arguments set it (a code reference, a method name or an array to accumulate into) and the argspec naming what it is passed.