我的 IF 语句和 LWP::Simple 有什么问题?

What's wrong with my IF statement and LWP::Simple?

我正在尝试创建一个简单的抓取工具,并且我正在使用 getstore(),但是当在 IF 语句中使用时,scirpt 不会创建 .txt 文件。我在那里做错了什么?

谢谢,

卡洛斯·N.

#!/usr/bin/perl -w
use strict;
use LWP::Simple;

my $url;
my $content;

print "Enter URL:";

chomp($url = <STDIN>);

$content = get($url);


if ($content =~ s%<(style|script)[^<>]*>.*?</>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->%%g) {

    $content = getstore($content,"../crawled_text.txt");
}   


die "Couldn't get $url" unless defined $content;

来自 LWP::Simple 文档:

my $code = getstore($url, $file)

Gets a document identified by a URL and stores it in the file. The return value is the HTTP response code.

您的第一个参数是一个剥离的 HTML 文件,可能不是 URL。您可以在代码中使用调试器或打印语句来了解有关变量内容以及程序是否进入 if 块的更多信息。

getstore 将 URL 作为参数并将其存储到文件中。你想要做的只是将内容存储在一个文件中,所以用这个代替

#!/usr/bin/perl

use strict;
use warnings;

use LWP::Simple;
use Path::Tiny;

my $url = shift || "https://perl.org";
my $content = get($url) or die "Couldn't get $url" ;

if ($content =~ s%<(style|script)[^<>]*>.*?</>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->%%g) {
  my $crawled_text = path("../crawled_text.txt");
  $crawled_text->spew_utf8($content)
}

我还做了一些小的样式更改,Path::Tiny 将内容保存到文件中。如果您愿意,可以使用默认的 openprint(或 say)。使用 shift 还允许将 URL 作为命令行的参数,这比提示用户输入它更符合习惯。