使用WWW :: Mechanize从多个链接下载文本

时间:2012-07-10 16:00:04

标签: perl hyperlink web-scraping www-mechanize

整整一周,我一直在尝试编写一个代码,该代码将从网页下载链接,然后遍历每个链接以转储写在每个链接页面上的内容。我下载的原始网页有500个链接到单独的网页,每个网页都包含重要信息。我只想降低一级。但是我有几个问题。

RECAP:我想从网页下载链接,并自动打开我的程序打印这些链接中包含的文本。我希望将它们打印在一个文件中。

1)当我从原始网站下载链接时,有用的链接不会完全写出来。 (即他们说“/festevents.nsf/all?openform”这不是一个可用的网页)

2)我无法打印页面的文本内容。我已经能够打印字体细节,但这没用。

     #Download all the modules I used#
     use LWP::UserAgent;
use HTML::TreeBuilder;
use HTML::FormatText;
use WWW::Mechanize;
use Data::Dumper;

#Download original webpage and acquire 500+ Links#

$url = "http://wx.toronto.ca/festevents.nsf/all?openform";

my $mechanize = WWW::Mechanize->new(autocheck => 1);

$mechanize->get($url);


my $title = $mechanize->title;

print "<b>$title</b><br />";


my @links = $mechanize->links;


foreach my $link (@links) {

   # Retrieve the link URL
   my $href = $link->url_abs;

  #
  # $URL1= get("$link");
  #
  my $ua = LWP::UserAgent->new;
  my $response = $ua->get($href);
  unless($response->is_success) {
    die $response->status_line;
  }
  my $URL1 = $response->decoded_content;
  die Dumper($URL1);

#This part of the code is just to "clean up" the text
$Format=HTML::FormatText->new;
$TreeBuilder=HTML::TreeBuilder->new;
$TreeBuilder->parse($URL1);
$Parsed=$Format->format($TreeBuilder);

open(FILE, ">TorontoParties.txt");
print FILE "$Parsed";
close (FILE);

 }

请帮帮我!我很绝望!如果可能的话,请向我解释每一步背后的逻辑?我一直在为此煎炸我的大脑一个星期,我希望帮助看到问题背后的其他人的逻辑。

1 个答案:

答案 0 :(得分:1)

工作太多了。研究WWW::Mechanize API以了解几乎所有功能都已内置。未测试的:

use strictures;
use WWW::Mechanize qw();
use autodie qw(:all);

open my $h, '>:encoding(UTF-8)', 'TorontoParties.txt';
my $mechanize = WWW::Mechanize->new;
$mechanize->get('http://wx.toronto.ca/festevents.nsf/all?openform');
foreach my $link (
    $mechanize->find_all_links(url_regex => qr'/festevents[.]nsf/[0-9a-f]{32}/[0-9a-f]{32}[?]OpenDocument')
) {
    $mechanize->get($link->url_abs);
    print {$h} $mechanize->content(format => 'text');
}
close $h;