Perl 使用Mojo::DOM在标题后提取未标记的文本

Perl 使用Mojo::DOM在标题后提取未标记的文本,perl,mojo-dom,Perl,Mojo Dom,我正在尝试使用Mojo::DOM从HTML文件中提取一些不带标记的文本(这方面我是新手)。特别是H2标题后的描述文本(文件中还有其他标题) 有谁能向我推荐一种获取“This text is the description”字符串的方法吗?试试这段代码,我刚刚添加了一个父元素: #!/usr/bin/perl use strict; use warnings; use Mojo::DOM; my $html = q{<div class="container"><h2>

我正在尝试使用Mojo::DOM从HTML文件中提取一些不带标记的文本(这方面我是新手)。特别是H2标题后的描述文本(文件中还有其他标题)


有谁能向我推荐一种获取“This text is the description”字符串的方法吗?

试试这段代码,我刚刚添加了一个父元素:

#!/usr/bin/perl

use strict;
use warnings;
use Mojo::DOM;


my $html = q{<div class="container"><h2>Description</h2>This text is the description<div class="footer">[<a href="/contrib/rev/1597/2795/">Edit description</a>
</div></div>};

my $dom = Mojo::DOM->new($html);

print $dom->at('div.container')->text();
可以遍历所有节点,也可以捕获那些不在HTML元素(标记)中的节点。然后使用以下事实,即您需要
h2
标记后面的节点

更准确地说,它跟随文本节点,该节点是(可识别的)
h2
标记节点的子节点

use warnings;
use strict;
use feature 'say';

use Mojo::DOM;

my $html = q(<h2>Description</h2> This text is the description <p>More...</p>);

my $dom = Mojo::DOM->new($html);

my $is_next = 0;

foreach my $node ($dom->descendant_nodes->each) { 
    my $par = $node->parent;
    if ($node->type eq 'text' and $par->type eq 'tag' and $par->tag eq 'h2') { 
        $is_next = 1;
    }   
    elsif ($is_next) {
        say $node;       #-->   This text is the description
        $is_next = 0;
    }   
}
使用警告;
严格使用;
使用特征“说”;
使用Mojo::DOM;
my$html=q(描述此文本是描述更多…

); my$dom=Mojo::dom->new($html); 我的$is_next=0; foreach my$node($dom->子代节点->每个节点){ 我的$par=$node->parent; 如果($node->type eq'text'和$par->type eq'tag'和$par->tag eq'h2'){ $is_next=1; } elsif($is_next){ 假设$node;#-->此文本是描述 $is_next=0; } }
通过询问前一个文本节点(标记的文本)或其父节点(标记),可以添加更多关于感兴趣的
h2
节点的标准(除非它确实是所有这样的节点)

也应该检查节点本身,例如查看它是否确实只是松散的文本,而不是实际的下一个标记

我已经用更复杂的HTML进行了测试;以上是一个几乎最小的可测试标记



在这个简单的例子中,
$dom->text
捕获所需的文本。但是,在更复杂的片段中,如果搜索的文本不在第一个元素之后,情况就不会如此。

您是否可以像父元素一样发布更多的HTML。
#!/usr/bin/perl

use strict;
use warnings;
use Mojo::DOM;


my $html = q{<div class="container"><h2>Description</h2>This text is the description<div class="footer">[<a href="/contrib/rev/1597/2795/">Edit description</a>
</div></div>};

my $dom = Mojo::DOM->new($html);

print $dom->at('div.container')->text();
print $dom->text();
use warnings;
use strict;
use feature 'say';

use Mojo::DOM;

my $html = q(<h2>Description</h2> This text is the description <p>More...</p>);

my $dom = Mojo::DOM->new($html);

my $is_next = 0;

foreach my $node ($dom->descendant_nodes->each) { 
    my $par = $node->parent;
    if ($node->type eq 'text' and $par->type eq 'tag' and $par->tag eq 'h2') { 
        $is_next = 1;
    }   
    elsif ($is_next) {
        say $node;       #-->   This text is the description
        $is_next = 0;
    }   
}