我是Perl脚本的新手。我想解析一个文本文件,对解析后的文本进行编码并附加到URL中。如果你知道的话,请指出我正确的资源。这是我的主要问题。
现在我尝试使用Perl中的LWP模块运行URL并将其保存在文本文件中。我使用以下程序连接到谷歌,但我收到“401 UNAUTHORIZED”错误。请帮忙 - 我应该在哪里提供我的用户身份验证详细信息和密码?
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request::Common qw(GET);
use HTTP::Cookies;
my $ua = LWP::UserAgent->new;
# Define user agent type
$ua->agent('Mozilla/8.0');
# Cookies
$ua->cookie_jar(
HTTP::Cookies->new(
file => 'mycookies.txt',
autosave => 1
)
);
# Request object
my $req = GET 'http://www.google.com';
# Make the request
my $res = $ua->request($req);
# Check the response
if ($res->is_success) {
print $res->content;
} else {
print $res->status_line . "\n";
}
exit 0;
答案 0 :(得分:1)
正如我在对您的问题的评论中提到的,WWW::Mechanize
是LWP
模块的包装器。它的使用类似于人们如何使用浏览器,它会自动执行cookie处理。
要解决您的直接问题,它提供的一种方法是credentials
:
提供用于所有站点和领域的HTTP基本身份验证的凭据,直到另行通知为止。
这是一个快速示例,类似于您自己的示例。用户凭据行已注释,因为我不希望谷歌需要它们。
#!/usr/bin/perl
use strict;
use warnings;
use WWW::Mechanize;
my $mech = WWW::Mechanize->new();
#$mech->credentials('username','password');
$mech->get('http://www.google.com');
if ($mech->success) {
$mech->dump_text();
#$mech->save_content('file.html');
} else {
print $mech->status();
}
总之,LWP
为您提供浏览网页的权力,WWW::Mechanize
让您更加方便。
答案 1 :(得分:-2)
您最好使用LWP::Simple
,因为这是一个非常简单明了的操作,用法示例:
use LWP::Simple;
$content = get("http://www.sn.no/");
die "Couldn't get it!" unless defined $content;