我可以使用Mojo::DOM及其CSS3選擇器來找出HTML文檔的DOCTYPE?關於我的其他問題,How should I process HTML META tags with Mojo::UserAgent?我想設置文檔的字符集,我需要知道要看什麼,並且doctype sniffing似乎是要做的。當文檔設置覆蓋服務器設置(或不設置)時,HTML和HTML 5對於HTML中的charsets具有不同的元標記。使用CSS3進行Doctype嗅探,特別是使用Mojo :: DOM
我完成任務沒有問題,因爲我可以抓住原始響應並使用正則表達式來查看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'}
],
現在怎麼辦我明白了嗎?
似乎沒有這樣做的內置方式,因爲doctype存儲在樹的頂層。我能想到的最好的辦法是:'my%ugly_tree = @ {$ dom-> root-> tree};我的($ doctype)= $ ugly_tree {doctype};'但這可能很脆弱。 – xxfelixxx
doctype只是另一個節點,您可以使用[child_nodes](http://mojolicio.us/perldoc/Mojo/DOM#child_nodes)等方法找到它們。 –