使用HTML :: TreeBuilder解析html

时间:2014-02-24 18:38:33

标签: perl html-treebuilder

我想解析html页面。使用

提取徽章,说明和徽章类型
      <div class="row">
       <div class="span8">
         <table id="badge-list">
           <tr>
             <td style="width: 25px;"></td>
             <td style="width: 200px;" class="badge-cell">
                <a class="badge-name" href="/badge/show/3/">
                    <span class="badge-icon bronze">&#8226;</span>
                     Editor
                </a>
                <span class="multiplier">x 3892</span></td>
              <td class="earned False">&nbsp;</td>
              <td>First edit</td>
           </tr>

我的perl代码如下,

我正在尝试使用以下代码

提取a class="badge-name"和其他详细信息
      my $tree = HTML::TreeBuilder->new();
      $tree->parse($content);
      my ($h1) = $tree->look_down('_tag', 'table', 'id', 'badge-list'); 
      my @tr = $h1->look_down('_tag', 'tr') ;

      foreach my  $tr (@tr) {
         my @tdList = $tr->look_down('_tag','td');

         foreach my $td ( @tdList) {
           if (my $a = $td->look_down('_tag','a')) {
               print $a->as_text , "\n";
               my $span = $a->look_down('_tag','span', 'class');
               print $span->attr('class');
           }
           else {
               my $text =  $td->as_text , "\n";    
               print "$text\n";
           }
      }

    }

此代码抛出警告Wide character in print at ..

2 个答案:

答案 0 :(得分:1)

look_down需要属性/值参数。

$a->look_down('_tag','span', 'class')

应该只是

$a->look_down('_tag','span')

答案 1 :(得分:0)

我建议添加“use utf8;”在脚本的开头添加支持非ASCII符号的打印。符号•是贬义的。

use utf8;