我正在使用TreeBuilder::XPath,如下所示:
use strict;
use warnings;
use LWP::Simple;
use HTML::TreeBuilder::XPath;
my $url='file:///C:/Users/Rockstar/workspace/abc/globals_func.html';
my $page = get($url) or die $!;
my $p = HTML::TreeBuilder::XPath->new_from_content( $page);
my @trips= $p->findnodes( '//div[@class="contents"]');
foreach my $trip (@trips){
print $trip->as_text;
}
在 HTML 文件中运行它后,我得到以下输出(全部在一行中):
ChainCtrlBuildChain() : ChainController.cChainCtrlDumpChain() : ChainController.cChainCtrlExit() : ChainController.cChainCtrlGetBitStreamChan() : ChainController.cChainCtrlInit() : ChainController.c.
但我希望它们显示如下(每个值一行):
ChainCtrlBuildChain() : ChainController.c
ChainCtrlDumpChain() : ChainController.c
ChainCtrlExit() : ChainController.c
ChainCtrlGetBitStreamChan() : ChainController.c
ChainCtrlInit() : ChainController.c.
我的HTML文件(仅显示“内容”的HTML代码):
<div class="contents">
 <ul>
<li>ChainCtrlBuildChain()
: <a class="el" href="_chain_controller_8c.html#acb2c56087a2072b6445a54c17662d118">ChainController.c</a>
</li>
<li>ChainCtrlDumpChain()
: <a class="el" href="_chain_controller_8c.html#a13ed5a02bf232b115b9a58cdd13dadd7">ChainController.c</a>
</li>
<li>ChainCtrlExit()
: <a class="el" href="_chain_controller_8c.html#a9e30e46ebc5411537efe95a286e27cb4">ChainController.c</a>
</li>
<li>ChainCtrlGetBitStreamChan()
: <a class="el" href="_chain_controller_8c.html#a00faa6e64ea466d4ec57339017e57e71">ChainController.c</a>
</li>
<li>ChainCtrlInit()
: <a class="el" href="_chain_controller_8c.html#aed300a388eff2fa9c7565025982faab1">ChainController.c</a>
</li>
</ul>
</div><!-- contents -->
我错过了什么?
最佳答案
您需要在 print
语句中添加新行。
print $trip->as_text."\n";
或者,您可以使用 say
自动执行此操作:
use feature 'say';
...
say $trip->as_text;
更新
您正在访问 div
元素,它为您提供数组中的一个元素以及 ul
的每个元素。要将 li
的每个元素放入一个数组元素中,您需要执行以下操作:
use feature 'say';
...
my @trips= $p->findnodes( '//div[@class="contents"]//li');
foreach my $trip (@trips){
say $trip->as_text;
}
这将访问 li
元素。
关于perl - 如何在单独的行上打印 HTML::Treebuilder 节点的文本内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17912823/