除了其他地方提到的 HTML 解析库之外,其他模块也具有 DOM 功能。参见例如Web::Query
和 Mojolicious' Mojo::DOM
。
这是一个使用Mojo::DOM
CSS3 选择器的示例:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.10.0;
use Mojo::DOM;
my $dom = Mojo::DOM->new(<<'HTML');
<div class="box notranslate" id="venueHours">
<h5 class="translate">Hours</h5>
<div class="status closed">Currently closed</div>
<div class="hours">
<div class="timespan">
<div class="openTime">
<div class="days">Mon,Tue,Wed,Thu,Sat</div>
<span class="hours"> 10:00 AM–6:00 PM</span>
</div>
</div>
<div class="timespan">
<div class="openTime">
<div class="days">Fri</div>
<span class="hours"> 10:00 AM–9:00 PM</span></div>
</div>
<div class="timespan">
<div class="openTime">
<div class="days">Sun</div>
<span class="hours"> 10:00 AM–5:00 PM</span>
</div>
</div>
</div>
</div>
HTML
say "div days:";
say $_->text for $dom->find('div.days')->each;
say "\nspan hours:";
say $_->text for $dom->find('span.hours')->each;
或等效地:
say "div days:";
say for $dom->find('div.days')->map(sub{$_->text})->each;
say "\nspan hours:";
say for $dom->find('span.hours')->map(sub{$_->text})->each;
输出:
div days:
Mon,Tue,Wed,Thu,Sat
Fri
Sun
span hours:
10:00 AM–6:00 PM
10:00 AM–9:00 PM
10:00 AM–5:00 PM
或者要获取对应天数的时间,可以使用openTimes
div 的子元素:
say "Open Times:";
say for $dom->find('div.openTime')
->map(sub{$_->children->each})
->map(sub{$_->text})
->each;
输出:
Open Times:
Mon,Tue,Wed,Thu,Sat
10:00 AM–6:00 PM
Fri
10:00 AM–9:00 PM
Sun
10:00 AM–5:00 PM
编辑: Daxim 已将类似的Web::Query
代码作为评论发布,因此我将在此处重新发布它以获得更好的格式。我没有尝试过,但我一般相信他的代码。假设 HTML 在一个变量中$html
:
use Web::Query qw();
my $w = Web::Query->new_from_html($html);
say "div days:";
say for $w->find('div.days')->text;
say "\nspan hours:";
say for $w->find('span.hours')->text;
say "Open Times:";
$w->find('div.openTime')->each(sub { say for $_->find('*')->text });