使用 Perl(或任何语言)在 Linux 中打开 URL?
我是 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;
I am new to Perl scripting. I wanted to parse a text file, encode the parsed text and attach in URL. Please point me to right resources if you know any. This is my major problem.
Now I try to get a URL running and save it in a text file using LWP module in Perl. I used the following program to connect to Google but I am getting "401 UNAUTHORIZED" error. Please help - where I should provide my user authentication details and password?
#!/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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如我在对您的问题的评论中提到的,
WWW::Mechanize
是LWP
模块的包装器。它的使用方式类似于浏览器的使用方式,并且它会自动进行 cookie 处理。为了解决您的直接问题,它提供的一种方法是
凭据
至:这是一个简单的示例,与您自己的示例类似。用户凭据行被注释,因为我不认为谷歌需要它们。
总之,
LWP
为您提供了浏览网页的能力,WWW::Mechanize
让您可以更方便地做您想要做的事情。As I have mentioned in my comment to your question,
WWW::Mechanize
is a wrapper forLWP
modules. It use resembles how one might use a browser, and it does cookie handling automatically.To address your direct question, one method it provides is
credentials
to:Here is a quick example, similar to your own. User credentials line is commented as I do not expect that google needs them.
In summary,
LWP
gives you the power to browser the web,WWW::Mechanize
makes it more convenient to Do What You Mean.你最好使用
LWP::Simple
,因为这是一个非常简单明了的操作,用法示例:You better use
LWP::Simple
as this is a quite simple and straightforward operation, usage example: