【发布时间】:2011-03-20 06:09:18
【问题描述】:
是否有一些强大的 perl 工具/库,例如 BeautifulSoup 到 python?
谢谢
【问题讨论】:
标签: perl beautifulsoup
是否有一些强大的 perl 工具/库,例如 BeautifulSoup 到 python?
谢谢
【问题讨论】:
标签: perl beautifulsoup
HTML::TreeBuilder::XPath 是解决大多数问题的好方法。
【讨论】:
我从未使用过 BeautifulSoup,但快速浏览一下它的文档,您可能想要HTML::TreeBuilder。它甚至可以很好地处理损坏的文档,并允许遍历已解析的树或查询项 - 查看 HTML::Element 中的 look_down 方法。
如果您喜欢/了解 XPath,请参阅 daxim 的推荐。如果您喜欢通过 CSS 选择器选择项目,请查看 Web::Scraper 或 Mojo::DOM。
【讨论】:
当您正在寻找强大的功能时,您可以使用 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 );
【讨论】: