【发布时间】:2016-06-22 09:35:27
【问题描述】:
我想解析 HTML5 标签?
当我解析它对<section> 标签的投诉时。我不希望它给出错误。
错误是“</section>”标签丢失。
我的输入是:-
<?xml version="1.0" encoding="utf-8"?><html xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/1999/xhtml" xmlns:m="http://www.w3.org/1998/Math/MathML" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" title="day" href="../css/main.css"/>
<title>Electric Potential and Electric Potential Energy</title>
<meta charset="UTF-8"/>
<meta name="dcterms.conformsTo" content="PXE 1.39 ProductLevelReuse"/>
<meta name="generator" content="PXE Tools version 1.39.69"/>
</head>
<body>
<section class="chapter" ><header><h1 class="title"><span class="number">20</span> Electric Potential and Electric Potential Energy</h1></header>
<section class="frontmatter">
<section class="listgroup"><header><h1 class="title">Big Ideas</h1></header>
<ol>
<li><p>Electric potential energy is similar to gravitational potential energy.</p></li>
</ol>
</section>
</section>
</body>
</html>
我的代码是:-
use warnings ;
use strict;
use HTML::Tidy;
my $file_name ="d:/perl/test.xhtml";
undef $/;
open xhtml_file, '<:encoding(UTF-8)', "$file_name" || die "no htm file found $!";
my $contents = <xhtml_file>;
close (xhtml_file);
$/ = "\n";
my $tidy = HTML::Tidy->new();
$tidy->ignore(
text => qr/DOCTYPE/,
text => qr/html/,
text => qr/meta/,
text => qr/header/
);
$tidy->parse( "foo.html", $contents );
for my $message ( $tidy->messages )
{
print $message->as_string, "\n";
}
错误日志是:-
foo.html (10:1) Error: <section> is not recognized!
foo.html (10:1) Warning: discarding unexpected <section>
foo.html (11:1) Error: <section> is not recognized!
foo.html (11:1) Warning: discarding unexpected <section>
foo.html (12:1) Error: <section> is not recognized!
foo.html (12:1) Warning: discarding unexpected <section>
foo.html (16:1) Warning: discarding unexpected </section>
foo.html (17:1) Warning: discarding unexpected </section>
我该如何解决?
【问题讨论】:
-
解析完之后要做什么?
-
对于初学者来说,HTML::Tiny 用于解析 HTML,而不是 XHTML(“HTML 的 XML 序列化”)
-
其次,关于缺少
</section>的错误是合法的。该 XML 格式不正确,因为您有一个未封闭的“节”元素。如果您按照应有的方式使用 XML 解析器,它肯定会抛出错误。如果你不希望它这样做,你应该修复错误。 -
来自www.tidyp.com: tidyp 是一个可以验证您的 HTML 并修改它以使其更干净和标准的程序。 tidyp 不验证 HTML 5.
标签: html perl html-parsing