【问题标题】:HTML Parsing: Get content from inner tagsHTML 解析:从内部标签获取内容
【发布时间】:2015-09-17 16:15:14
【问题描述】:

测试输入文件:

# cat test.html 
<div>line 1<div>Another 1</div></div>
<div>line 2<div>Another 2</div></div>
<div>line 3<div>Another 3</div></div>

预期输出:

Another 1
Another 2
Another 3

脚本:

#!/usr/bin/perl
use warnings;
use strict;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new;

# $tree->ignore_ignorable_whitespace(0);
# $tree->no_space_compacting(1)

$tree->parse_file("test.html");

foreach my $a ($tree->find("div")) 
{
  print $a->as_text."\n";
}

脚本输出:

line 1Another 1
Another 1
line 2Another 2
Another 2
line 3Another 3
Another 3

问题: 我正在寻求帮助,仅从 inner div 标签中提取内容。我的脚本首先输出line 1Another 1,然后输出Another 1。但是,我只对Another 1 感兴趣。

我尝试使用 ignore_ignorable_whitespaceno_space_compacting(如脚本 cmets 中所示),但没有成功。要么我没有正确使用它,要么我叫错了树。

【问题讨论】:

    标签: html perl html-parsing


    【解决方案1】:

    当您只需要内部元素时,您会找到所有 div 元素。 findnodes 方法采用 XPath 表达式,因此您可以编写

    print $_->as_text, "\n" for $tree->findnodes('div/div')
    

    【讨论】:

      猜你喜欢
      • 2012-04-13
      • 2015-07-02
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 2013-07-07
      • 1970-01-01
      相关资源
      最近更新 更多