【问题标题】:Download files with perl lwp linkextractor使用 perl lwp linkextractor 下载文件
【发布时间】:2020-03-18 13:41:17
【问题描述】:

我正在尝试从网页下载文件。

首先我使用链接提取器获取链接,然后我想使用 lwp 下载它们 我是 perl 编程新手。

我做了以下代码...

#!/usr/bin/perl

use strict;
use warnings;

use HTML::TableExtract;
use HTML::LinkExtractor;
use LWP::Simple qw(get);
use Archive::Zip;

my $html = get $ARGV[0];

my $te = HTML::TableExtract->new(
    keep_html => 1,
    headers => [qw( column1 column2 )],
);
$te->parse($html);

# I get only the first row
my ($row) = $te->rows;

my $LXM = new HTML::LinkExtractor(undef,undef,1);
$LXM->parse(\$$row[0]);
my ($t) = $LXM->links;

my $LXS = new HTML::LinkExtractor(undef,undef,1);
$LXS->parse(\$$row[1]);
my ($s) = $LXS->links;

#-------
for (my $i=0; $i < scalar(@$s); $i++) {
  print "$$s[$i]{_TEXT} $$s[$i]{href} $$t[$i]{href} \n";
  my $file = '/tmp/$$s[$i]{_TEXT}';
  my $url = $$s[$i]{href};
  my $content = getstore($url, $file);
  die "Couldn't get it!" unless defined $content;
}

我收到以下错误

Undefined subroutine &main::getstore called at ./geturlfromtable.pl line 35.

提前致谢!

【问题讨论】:

    标签: perl url get lwp html-tableextract


    【解决方案1】:

    LWP::Simple 可以通过两种不同的方式加载。

    use LWP::Simple;
    

    这会加载模块并使其所有功能都可用于您的程序。

    use LWP::Simple qw(list of function names);
    

    这会加载模块并仅提供您请求的特定功能集。

    你有这个代码:

    use LWP::Simple qw(get);
    

    这使得get() 函数可用,但getstore() 函数不可用。

    要解决此问题,请将getstore() 添加到您的函数列表中。

    use LWP::Simple qw(get getstore);
    

    或者(可能更简单)删除函数列表。

    use LWP::Simple;
    

    更新:如果我添加几个样式点,我希望你不介意。

    首先,您使用的是一个非常旧的模块 - HTML::LinkExtractor。它已经快十五年没有更新了。我建议改为查看HTML::LinkExtor。

    其次,您的代码使用了很多引用,但您使用它们的方式确实过于复杂。例如,你有\$$row[0],你真的只需要$row-&gt;[0]。同样,$$s[$i]{href} 写成$s-&gt;[$i]{href} 对大多数人来说也很容易理解。

    接下来,您使用 C 风格的 for 循环并迭代数组的索引。使用foreach 从零迭代到数组中的最后一个索引通常更简单。

    foreach my $i (0 .. $#$s) {
      print "$s->[$i]{_TEXT} $s->[$i]{href} $t->[$i]{href} \n";
      my $file = "/tmp/$s->[$i]{_TEXT}";
      my $url = $s->[$i]{href};
      my $content = getstore($url, $file);
      die "Couldn't get it!" unless defined $content;
    }
    

    最后,您似乎对getstore() 返回的内容有些困惑。它返回 HTTP 响应代码。所以它永远不会是未定义的。如果检索内容时出现问题,您将收到 500 或 403 或类似的信息。

    【讨论】:

    • 谢谢戴夫!现在我的变量有问题......我希望将文件保存为 url my $file = '/tmp/$$s[$i]{_TEXT}'; 的 _TEXT 肯定它被错误地声明了
    • @nixv:嗯,是的。如果要扩展变量,至少要将该字符串放在双引号中。
    • 谢谢!还有你的风格点!!!现在,我在解压缩下载的文件时遇到问题:(
    猜你喜欢
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2013-12-20
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多