4

我一直坚持这一天。我对在 perl 中解析/抓取仍然很陌生,但我认为我已经完成了它。我一直在尝试使用不同的 perl 模块(tokeparser,tokeparser:简单,网络解析器和其他一些)......我有以下字符串(实际上它实际上是一个完整的HTML页面,但这只是显示相关部分..我正在尝试提取“text1”和“text1_a”。 .等等(“text1”等只是作为一个例子放在那里)......所以基本上我认为我需要先从每个中提取这个:

"<span style="float: left;">test1</span>test1_a"

然后解析它以获取 2 个值。我不知道为什么这给我带来了这么多麻烦,因为我认为我可以在 tokeparser:simple 中做到这一点,但我似乎无法返回 DIV 内部的值,我想知道是不是因为它包含另一组标签(标签)

字符串(代表 html 网页)

<div id="dataID" style="font-size: 8.5pt; width: 250px; color: rgb(0, 51, 102); margin-right: 10px; float: right;">
<div style="width: 250px; text-align: right;"><span style="float: left;">test1</span>test1_a</div>
<div style="width: 250px; text-align: right;"><span style="float: left;">test2</span>test2_a</div>
<div style="width: 250px; text-align: right;"><span style="float: left;">test3</span>test3_a</div>

我在 perl web 解析器模块中的尝试:

my $uri  = URI->new($theurl);

my $proxyscraper = scraper {
process 'div[style=~"width: 250px; text-align: right;"]',
'proxiesextracted[]' => scraper {
process '.style',  style => 'TEXT';
};
result 'proxiesextracted';

我只是有点盲目地试图理解 web:parser 模块,因为它基本上没有文档,所以我只是从模块中包含的示例和我在互联网上找到的示例中拼凑起来..任何建议非常感谢。

4

2 回答 2

5

如果你想要一个 DOM 解析器(更容易使用树浏览,稍微慢一些)。试试HTML::TreeBuilder

HTML::Element手册页(包括模块)

Note also that look_down considers "" (empty-string) and undef to be

不同的东西,在属性值。所以这:

  $h->look_down("alt", "")

这使我们得到您的答案:

use HTML::TreeBuilder;

# check html::treebuilder pod, there are a few ways to construct (file, fh, html string)
my $tb = HTML::TreeBuilder->new_from_(constructor)

$tb->look_down( _tag => 'div', style => '' )->as_text;
于 2010-07-15T03:46:54.057 回答
1

使用Web::Scraper,尝试:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper::Simple;
use Web::Scraper;

$Data::Dumper::Indent = 1;

my $html = '<div id="dataID" style="font-size: 8.5pt; width: 250px; color: rgb(0, 51, 102); margin-right$
<div style="width: 250px; text-align: right;"><span style="float: left;">test1</span>test1_a</div>
<div style="width: 250px; text-align: right;"><span style="float: left;">test2</span>test2_a</div>
<div style="width: 250px; text-align: right;"><span style="float: left;">test3</span>test3_a</div>';


my $proxyscraper = scraper {
    process '//div[@id="dataID"]/div', 'proxiesextracted[]' => scraper {
       process '//span', 'data1' => 'TEXT';
       process '//text()', 'data2' => 'TEXT';
     }
};

my $results = $proxyscraper->scrape( $html );

print Dumper($results);

它给:

$results = {
  'proxiesextracted' => [
    {
      'data2' => 'test1_a',
      'data1' => 'test1'
    },
    {
      'data2' => 'test2_a',
      'data1' => 'test2'
    },
    {
      'data2' => 'test3_a',
      'data1' => 'test3'
    }
  ]
};

希望这可以帮助

于 2010-07-15T15:46:47.020 回答