简体   繁体   English

使用LWP和Perl登录网站

[英]Loggin into website with LWP and Perl

Somewhat inexperienced programmer here trying to write a program to log into my courses site and download all the content (lectures homeworks etc). 有点没经验的程序员在这里尝试编写程序登录我的课程网站并下载所有内容(讲座家庭作业等)。 Obviously it is a password protected site so I have to give it that. 显然它是一个受密码保护的网站,所以我必须给它。 I understand LWP::UserAgent and the likes well enough, and that I need to use credentials. 我理解LWP :: UserAgent和类似的东西,我需要使用凭据。 What I cannot figure out is how to get to the next page. 我无法弄清楚的是如何进入下一页。 I can go to the log-in, but how does perl get the result of my log-in? 我可以进入登录,但perl如何获得登录结果?

code example (i pulled out the log-info obviously): 代码示例(我明显地提取了日志信息):

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $url = 'login URL';
$ua -> credentials(
  $url,
  '',
  'user',
  'pass'
);
my $response = $ua ->get($url);
print $response->content; 

the content from response is the same content as what I would have got as if I had not passed any credentials. 来自响应的内容与我所获得的内容相同,就像我没有通过任何凭据一样。 Obviously I'm missing something here.... 显然我在这里遗漏了一些东西....

Oh one other thing my own courses site does not have a unique url as far as I know. 哦,据我所知,我自己的课程网站没有一个独特的网址。

您可能希望使用WWW :: Mechanize ,LWP :: UserAgent的子类,其设计更像浏览器,允许您浏览已经为您处理的cookie存储的网站页面。

You only use credentials if the site uses HTTP basic auth, in which case you don't "log in", you just pass the credentials with every request. 如果站点使用HTTP基本身份验证,您只使用credentials ,在这种情况下,您不“登录”,只需在每个请求中传递凭据。

If the site has a form based login system, then you need to use cookie_jar and request the form's action URI with whatever data it expects. 如果站点具有基于表单的登录系统,那么您需要使用cookie_jar并使用其预期的任何数据请求表单的操作URI。

#!/usr/bin/perl

use LWP::UserAgent;
use HTTP::Cookies;

my  $ua=LWP::UserAgent->new(timeout => 20);
    $ua->agent('Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.8) Gecko/20100202 MRA 5.5 (build 02842) Firefox/3.5.8');
    $ua->requests_redirectable(0);

my  $cook = HTTP::Cookies->new;
    $ua->cookie_jar($cook);

print = requester('http://urlexample/login.php', 'login=yourlogin&password=pass' )->as_string;

sub requester
{
    my $type = 'GET';
    if($_[1]){$type = 'POST'}   
    my $req = HTTP::Request->new($type => $_[0]);
    $req->content_type('application/x-www-form-urlencoded; charset=UTF-8');
    if($_[1]){$req->content($_[1])}
    my $res = $ua->request($req);
    return $res;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM