【发布时间】:2015-12-05 00:50:36
【问题描述】:
我可以使用Mojo::DOM 及其CSS3 选择器来确定HTML 文档的DOCTYPE 吗?与我的另一个问题有关,How should I process HTML META tags with Mojo::UserAgent? 我想在哪里设置文档的字符集,我需要知道要查看什么,doctype sniffing 似乎是这样做的方法。当文档设置覆盖服务器设置(或非设置)时,HTML 和 HTML 5 对 HTML 中的字符集具有不同的元标记。
我完成任务没有问题,因为我可以获取原始响应并使用正则表达式来查看 DOCTYPE。 Since the browser DOMs seem to be able to get the DOCTYPE,我被我应该能够得到它的想法所感染。但是,由于缺乏示例,我认为没有人会按照我认为我应该做的方式去做。
我尝试了很多愚蠢的方法,但我的 CSS 功夫很弱:
use v5.20;
use feature qw(signatures);
no warnings qw(experimental::signatures);
use Mojo::DOM;
my $html = do { local $/; <DATA> };
my $dom = Mojo::DOM->new( $html );
say "<title> is => ", $dom->find( 'head title' )->map( 'text' )->each;
say "Doctype with find is => ", $dom->find( '!doctype' )->map( 'text' )->each;
say "Doctype with nodes is => ", $dom->[0];
__DATA__
<!DOCTYPE html>
<head>
<title>This is a title</title>
</head>
<body>
<h1>Level 1</h1>
</body>
</html>
当我转储 $dom 对象时,我在树中看到 DOCTYPE:
$VAR1 = bless( do{\(my $o = bless( {
'tree' => [
'root',
[
'text',
'',
${$VAR1}->{'tree'}
],
[
'doctype',
' html',
${$VAR1}->{'tree'}
],
现在我该怎么做?
【问题讨论】:
-
似乎没有内置的方法可以做到这一点,因为文档类型存储在树的顶层。我能想到的最好的办法是:
my %ugly_tree = @{ $dom->root->tree }; my ($doctype) = $ugly_tree{doctype};但这可能很脆弱。 -
doctype只是另一个节点,您可以使用child_nodes等方法找到它们。
标签: html perl css mojolicious mojo-dom