Parse html reliably
use HTML::HTML5::Parser; my $parser = HTML::HTML5::Parser->new; my $doc = $parser->parse_string(<<'EOT'); <!doctype html> <title>Foo</title> <p><b><i>Foo</b> bar</i>. <p>Baz</br>Quux. EOT my $fdoc = $parser->parse_file( $html_file_name ); my $fhdoc = $parser->parse_fh( $html_file_handle );
This library is substantially the same as the non-CPAN module Whatpm::HTML. Changes include:
Provides an XML::LibXML-like \s-1DOM\s0 interface. If you usually use XML::LibXML's \s-1DOM\s0 parser, this should be a drop-in solution for tag soup \s-1HTML\s0.
Constructs an XML::LibXML::Document as the result of parsing.
Via bundling and modifications, removed external dependencies on non-CPAN packages.
$parser = HTML::HTML5::Parser->new; # or $parser = HTML::HTML5::Parser->new(no_cache => 1); The constructor does nothing interesting besides take one flag argument, \*(C`no_cache => 1\*(C', to disable the global element metadata cache. Disabling the cache is handy for conserving memory if you parse a large number of documents, however, class methods such as \*(C`/source_line\*(C' will not work, and must be run from an instance of this parser.
$doc = $parser->parse_file( $html_file_name [,\%opts] ); This function parses an \s-1HTML\s0 document from a file or network; $html_file_name can be either a filename or an \s-1URL\s0. Options include 'encoding' to indicate file encoding (e.g. 'utf-8') and 'user_agent' which should be a blessed \*(C`LWP::UserAgent\*(C' (or HTTP::Tiny) object to be used when retrieving URLs. If requesting a \s-1URL\s0 and the response Content-Type header indicates an XML-based media type (such as \s-1XHTML\s0), XML::LibXML::Parser will be used automatically (instead of the tag soup parser). The \s-1XML\s0 parser can be told to use a \s-1DTD\s0 catalogue by setting the option 'xml_catalogue' to the filename of the catalogue. \s-1HTML\s0 (tag soup) parsing can be forced using the option 'force_html', even when an \s-1XML\s0 media type is returned. If an options hashref was passed, parse_file will set $options->{'parser_used'} to the name of the class used to parse the \s-1URL\s0, to allow the calling code to double-check which parser was used afterwards. If an options hashref was passed, parse_file will set $options->{'response'} to the HTTP::Response object obtained by retrieving the \s-1URI\s0. $doc = $parser->parse_fh( $io_fh [,\%opts] ); \*(C`parse_fh()\*(C' parses a \s-1IOREF\s0 or a subclass of \*(C`IO::Handle\*(C'. Options include 'encoding' to indicate file encoding (e.g. 'utf-8'). $doc = $parser->parse_string( $html_string [,\%opts] ); This function is similar to \*(C`parse_fh()\*(C', but it parses an \s-1HTML\s0 document that is available as a single string in memory. Options include 'encoding' to indicate file encoding (e.g. 'utf-8'). Wrappers for the parse_* functions. These should be roughly compatible with the equivalently named functions in XML::LibXML. Note that \*(C`load_xml\*(C' first attempts to parse as real \s-1XML\s0, falling back to \s-1HTML5\s0 parsing; \*(C`load_html\*(C' just goes straight for \s-1HTML5\s0. $fragment = $parser->parse_balanced_chunk( $string [,\%opts] ); This method is roughly equivalent to XML::LibXML's method of the same name, but unlike XML::LibXML, and despite its name it does not require the chunk to be \*(L"balanced\*(R". This method is somewhat black magic, but should work, and do the proper thing in most cases. Of course, the proper thing might not be what you'd expect! I'll try to keep this explanation as brief as possible... Consider the following string: <b>Hello</b></td></tr> <i>World</i> What is the proper way to parse that? If it were found in a document like this: <html> <head><title>X</title></head> <body> <div> <b>Hello</b></td></tr> <i>World</i> </div> </body> </html> Then the document would end up equivalent to the following \s-1XHTML:\s0 <html> <head><title>X</title></head> <body> <div> <b>Hello</b> <i>World</i> </div> </body> </html> The superfluous \*(C`</td></tr>\*(C' is simply ignored. However, if it were found in a document like this: <html> <head><title>X</title></head> <body> <table><tbody><tr><td> <b>Hello</b></td></tr> <i>World</i> </td></tr></tbody></table> </body> </html> Then the result would be: <html> <head><title>X</title></head> <body> <i>World</i> <table><tbody><tr><td> <b>Hello</b></td></tr> </tbody></table> </body> </html> Yes, \*(C`<i>World</i>\*(C' gets hoisted up before the \*(C`<table>\*(C'. This is weird, I know, but it's how browsers do it in real life. So what should: $string = q{<b>Hello</b></td></tr> <i>World</i>}; $fragment = $parser->parse_balanced_chunk($string); actually return? Well, you can choose... $string = q{<b>Hello</b></td></tr> <i>World</i>};
$frag1 = $parser->parse_balanced_chunk($string, {within=>'div'}); say $frag1->toString; # <b>Hello</b> <i>World</i>
$frag2 = $parser->parse_balanced_chunk($string, {within=>'td'}); say $frag2->toString; # <i>World</i><b>Hello</b> If you don't pass a \*(L"within\*(R" option, then the chunk is parsed as if it were within a \*(C`<div>\*(C' element. This is often the most sensible option. If you pass something like \*(C`{ within => "foobar" }\*(C' where \*(L"foobar\*(R" is not a real \s-1HTML\s0 element name (as found in the \s-1HTML5\s0 spec), then this method will croak; if you pass the name of a void element (e.g. "br" or "meta") then this method will croak; there are a handful of other unsupported elements which will croak (namely: "noscript", "noembed", "noframes"). Note that the second time around, although we parsed the string "as if it were within a \*(C`<td>\*(C' element", the \*(C`<i>Hello</i>\*(C' bit did not strictly end up within the \*(C`<td>\*(C' element (not even within the \*(C`<table>\*(C' element!) yet it still gets returned. We'll call things such as this \*(L"outliers\*(R". There is a \*(L"force_within\*(R" option which tells parse_balanced_chunk to ignore outliers: $frag3 = $parser->parse_balanced_chunk($string, {force_within=>'td'}); say $frag3->toString; # <b>Hello</b> There is a boolean option \*(L"mark_outliers\*(R" which marks each outlier with an attribute (\*(C`data-perl-html-html5-parser-outlier\*(C') to indicate its outlier status. Clearly, this is ignored when you use \*(L"force_within\*(R" because no outliers are returned. Some outliers may be XML::LibXML::Text elements; text nodes don't have attributes, so these will not be marked with an attribute. A last note is to mention what gets returned by this method. Normally it's an XML::LibXML::DocumentFragment object, but if you call the method in list context, a list of the individual node elements is returned. Alternatively you can request the data to be returned as an XML::LibXML::NodeList object: # Get an XML::LibXML::NodeList my $list = $parser->parse_balanced_chunk($str, {as=>'list'}); The exact implementation of this method may change from version to version, but the long-term goal will be to approach how common desktop browsers parse \s-1HTML\s0 fragments when implementing the setter for \s-1DOM\s0's \*(C`innerHTML\*(C' attribute.
The push parser and SAX-based parser are not supported. Trying to change an option (such as recover_silently) will make HTML::HTML5::Parser carp a warning. (But you can inspect the options.)
Error handling is obviously different to XML::LibXML, as errors are (bugs notwithstanding) non-fatal. Get/set an error handling function. Must be set to a coderef or undef. The error handling function will be called with a single parameter, a HTML::HTML5::Parser::Error object. Returns a list of errors that occurred during the last parse. See HTML::HTML5::Parser::Error.
The module provides a few methods to obtain additional, non-DOM data from \s-1DOM\s0 nodes. $pubid = $parser->dtd_public_id( $doc ); For an XML::LibXML::Document which has been returned by HTML::HTML5::Parser, using this method will tell you the Public Identifier of the \s-1DTD\s0 used (if any). $sysid = $parser->dtd_system_id( $doc ); For an XML::LibXML::Document which has been returned by HTML::HTML5::Parser, using this method will tell you the System Identifier of the \s-1DTD\s0 used (if any). $element = $parser->dtd_element( $doc ); For an XML::LibXML::Document which has been returned by HTML::HTML5::Parser, using this method will tell you the root element declared in the \s-1DTD\s0 used (if any). That is, if the document has this doctype: <!doctype html> ... it will return \*(L"html\*(R". This may return the empty string if a \s-1DTD\s0 was present but did not contain a root element; or undef if no \s-1DTD\s0 was present. $mode = $parser->compat_mode( $doc ); Returns 'quirks', 'limited quirks' or undef (standards mode). $charset = $parser->charset( $doc ); The character set apparently used by the document. ($line, $col) = $parser->source_line( $node ); $line = $parser->source_line( $node ); In scalar context, \*(C`source_line\*(C' returns the line number of the source code that started a particular node (element, attribute or comment). In list context, returns a tuple: $line, $column, $implicitness. Tab characters count as one column, not eight. $implicitness indicates that the node was not explicitly marked up in the source code, but its existence was inferred by the parser. For example, in the following markup, the \s-1HTML\s0, \s-1TITLE\s0 and P elements are explicit, but the \s-1HEAD\s0 and \s-1BODY\s0 elements are implicit. <html> <title>I have an implicit head</title> <p>And an implicit body too!</p> </html> (Note that implicit elements do still have a line number and column number.) The implictness indicator is a new feature, and I'd appreciate any bug reports where it gets things wrong. XML::LibXML::Node has a \*(C`line_number\*(C' method. In general this will always return 0 and HTML::HTML5::Parser has no way of influencing it. However, if you install XML::LibXML::Devel::SetLineNumber on your system, the \*(C`line_number\*(C' method will start working (at least for elements).
<http://suika.fam.cx/www/markup/html/whatpm/Whatpm/HTML.html>.
HTML::HTML5::Writer, HTML::HTML5::Builder, XML::LibXML, XML::LibXML::PrettyPrint, XML::LibXML::Devel::SetLineNumber.
Toby Inkster, <[email protected]>
Copyright (C) 2007-2011 by Wakaba
Copyright (C) 2009-2012 by Toby Inkster
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
\s-1THIS\s0 \s-1PACKAGE\s0 \s-1IS\s0 \s-1PROVIDED\s0 \*(L"\s-1AS\s0 \s-1IS\s0\*(R" \s-1AND\s0 \s-1WITHOUT\s0 \s-1ANY\s0 \s-1EXPRESS\s0 \s-1OR\s0 \s-1IMPLIED\s0 \s-1WARRANTIES\s0, \s-1INCLUDING\s0, \s-1WITHOUT\s0 \s-1LIMITATION\s0, \s-1THE\s0 \s-1IMPLIED\s0 \s-1WARRANTIES\s0 \s-1OF\s0 \s-1MERCHANTIBILITY\s0 \s-1AND\s0 \s-1FITNESS\s0 \s-1FOR\s0 A \s-1PARTICULAR\s0 \s-1PURPOSE\s0.