【问题标题】:How to convert HTML file into a hash in Perl?如何在 Perl 中将 HTML 文件转换为哈希?
【发布时间】:2013-08-08 22:09:35
【问题描述】:

有没有什么简单的方法可以将 HTML 文件转换为 Perl 哈希?例如一个工作的 Perl 模块之类的?

我在 cpan.org 上搜索,但没有找到任何可以做我想做的事。我想做这样的事情:

use Example::Module;
my $hashref = Example::Module->new('/path/to/mydoc.html');

在此之后,我想引用第二个 div 元素,如下所示:

my $second_div = $hashref->{'body'}->{'div'}[1];
# or like this:
my $second_div = $hashref->{'body'}->{'div'}->findByClass('.myclassname');
# or like this:
my $second_div = $hashref->{'body'}->{'div'}->findById('#myid');

有什么可行的解决方案吗?

【问题讨论】:

    标签: perl html-parsing perl-module


    【解决方案1】:

    HTML::TreeBuilder::XPath 为您提供比简单哈希更多的功能。

    摘自:

      use HTML::TreeBuilder::XPath;
      my $tree = HTML::TreeBuilder::XPath->new;
      $tree->parse_file( "mypage.html");
    
      my $nb=$tree->findvalue('/html/body//p[@class="section_title"]/span[@class="nb"]');
      my $id=$tree->findvalue('/html/body//p[@class="section_title"]/@id');
      my $p= $html->findnodes('//p[@id="toto"]')->[0];
    
      my $link_texts= $p->findvalue( './a'); # the texts of all a elements in $p
    
      $tree->delete; # to avoid memory leaks, if you parse many HTML documents 
    

    更多关于XPath

    【讨论】:

      【解决方案2】:

      Mojo::DOM (docs found here) 构建一个简单的 DOM,可以以 CSS 选择器样式访问:

      # Find
      say $dom->at('#b')->text;
      say $dom->find('p')->pluck('text');
      say $dom->find('[id]')->pluck(attr => 'id');
      

      如果您使用的是 xhtml,您也可以使用 XML::Simple,它会生成与您描述的数据结构相似的数据结构。

      【讨论】:

        猜你喜欢
        • 2012-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-13
        • 1970-01-01
        • 2017-01-06
        • 2020-01-02
        • 2012-01-17
        相关资源
        最近更新 更多