1

我是 Perl 脚本的新手。我想解析一个文本文件,对解析后的文本进行编码并附加在 URL 中。如果您知道任何资源,请指出我正确的资源。这是我的主要问题。

现在,我尝试使用 Perl 中的 LWP 模块运行 URL 并将其保存在文本文件中。我使用以下程序连接到 Google,但收到“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;
4

2 回答 2

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更方便地按照您的意思行事。

于 2011-05-10T00:13:08.687 回答
-2

您最好使用LWP::Simple,因为这是一个非常简单直接的操作,用法示例:

 use LWP::Simple;
 $content = get("http://www.sn.no/");
 die "Couldn't get it!" unless defined $content;
于 2011-05-09T06:52:37.530 回答