0

HTMLには非常に多くの異なるパーサーがあるため、厳密なパーサーを選択するのは困難です。

私の仕事は、 URLを読み取り<table>、特定のIDを持つを見つけてから、このテーブルのすべての行を解析し<tr>てコンテンツ(テキスト)だけでなく、タグ内の<a>リンクと<img>画像も解析することです。<td>

また、データをカテゴリに並べ替えるために、各行要素のクラスをチェックする必要があります。

私の最良の選択は何でしょうか、どのライブラリとどのメソッドを使用して結果をすばやく取得する必要がありますか?


解析したい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>
4

1 に答える 1

1

Web::Queryを使用します。そのメソッドfindおよびtextおよびを使用しますattr

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']
# ]
于 2012-07-02T22:07:08.820 に答える