【问题标题】:perl html parsing lib/toolperl html 解析库/工具
【发布时间】:2011-03-20 06:09:18
【问题描述】:

是否有一些强大的 perl 工具/库,例如 BeautifulSoup 到 python?

谢谢

【问题讨论】:

    标签: perl beautifulsoup


    【解决方案1】:

    HTML::TreeBuilder::XPath 是解决大多数问题的好方法。

    【讨论】:

      【解决方案2】:

      我从未使用过 BeautifulSoup,但快速浏览一下它的文档,您可能想要HTML::TreeBuilder。它甚至可以很好地处理损坏的文档,并允许遍历已解析的树或查询项 - 查看 HTML::Element 中的 look_down 方法。

      如果您喜欢/了解 XPath,请参阅 daxim 的推荐。如果您喜欢通过 CSS 选择器选择项目,请查看 Web::ScraperMojo::DOM

      【讨论】:

        【解决方案3】:

        当您正在寻找强大的功能时,您可以使用 XML::LibXML 来解析 HTML。这样做的好处是您拥有 Perl 可用于处理文档的最快和最好的 XML 工具链(MSXML 除外,它仅适用于 MS)的所有功能,包括 XPath 和 XSLT(如果您使用另一个,则需要重新解析)解析器比 XML::LibXML)。

        use strict;
        use warnings;
        use XML::LibXML;
        # In 1.70, the recover and suppress_warnings options won't shup up the
        # warnings. Hence, a workaround is needed to keep the messages away from
        # the screen.
        sub shutup_stderr {
            my( $subref, $bufref ) = @_;
            open my $fhbuf, '>', $bufref;
            local *STDERR = $fhbuf;
            $subref->(); # execute code that needs to be shut up
            return;
        }
        # ==== main ============================================================
        my $url = shift || 'http://www.google.de';
        my $parser = XML::LibXML->new( recover => 2 ); # suppress_warnings => 1
        # Note that "recover" and "suppress_warnings" might not work - see above.
        # https://rt.cpan.org/Public/Bug/Display.html?id=58024
        my $dom; # receive document
        shutup_stderr
            sub { $dom = $parser->load_html( location => $url ) }, # code
            \my $errmsg; # buffer
        # Now process document as XML.
        my @nodes = $dom->getElementsByLocalName( 'title' );
        printf "Document title: %s\n", $_->textContent for @nodes;
        printf "Lenght of error messages: %u\n", length $errmsg;
        print '-' x 72, "\n";
        print $dom->toString( 1 );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-03
          • 2011-10-10
          • 2012-10-26
          • 2012-12-12
          • 2015-12-02
          • 2015-07-02
          • 2012-10-25
          相关资源
          最近更新 更多