【问题标题】:Perl HTML Parser for tables用于表格的 Perl HTML 解析器
【发布时间】:2012-07-03 07:41:23
【问题描述】:

HTML 有很多不同的解析器,很难选择正确的一个。

我的任务是读取 url 并找到具有特定 id<table>,然后解析此表的所有 <tr> 行以获取内容(文本),还有<a> 链接和<img> 图片在<td> 标签内。

我还需要检查每个行元素的 class 以将数据分类到类别。

什么是我最好的选择,我应该使用哪个库和什么方法来快速获得结果?


我要解析的部分 HTML 代码示例:

<table id="t1">
  <tr class="r1">
    <td class="c1"><a href="..."><img height="50" src="..." width="50" /></a></td>
    <td class="c2">
      <div class="d1">
        <ul class="u1">
          <li class="l1"><a href="..." rel='...'>text here</a></li>
          <li class="l2"><a href="..." rel='...'>text here</a></li>
        </ul>
      </div>
      <div class="d2">
        <a href="...">text here</a>
      </div>
    </td>
    <td class="c3">
      <div ...>...</div>
      <div class="d2">
        <a href="...">text here</a>
      </div>
    </td>
    <td class="c4">text here</td>
    <td class="c5">text here</td>
  </tr>
  ...
</table>

【问题讨论】:

    标签: html perl parsing html-parsing


    【解决方案1】:

    使用Web::Query。使用它的方法findtextattr

    use List::Gen qw(mapn);
    use Web::Query 'wq';
    
    sub classify {
        my ($l) = @_; my %r;
        mapn { push @{ $r{$_[0]} }, $_[1] } 2, @$l; return %r;
    };
    
    my $w = wq('file:///tmp/so11301348.html');
    my %rows = classify $w
        # find a <table> with specific id
        ->find('table#t1')
        # parse all <tr> rows of this table for content (text)
        # check class for each row element to sort data to categories
        ->find('tr')->map(sub {
            my (undef, $tr) = @_;
            return $tr->attr('class') => $tr->text;
        });
    # (
    #     '' => [
    #         ' ... '
    #     ],
    #     r1 => [
    #         'text heretext heretext here...text heretext heretext here'
    #     ]
    # )
    
    my $links_images = $w
    # but also <a> links and <img> images within <td> tags
    ->find('td a, td img')
    ->map(sub {
        my (undef, $e) = @_;
        return $e->attr('src')
            ? [img => $e->attr('src') => $e->attr('alt')]
            : [a => $e->attr('href') => $e->text];
    });
    # [
    #     ['a',   '...', ''],
    #     ['img', '...', ''],
    #     ['a',   '...', 'text here'],
    #     ['a',   '...', 'text here'],
    #     ['a',   '...', 'text here'],
    #     ['a',   '...', 'text here']
    # ]
    

    【讨论】:

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