2011-10-25 29 views
1

我需要登录到网站,解析HTML页面并提取特定HTML标记之间的值。在Perl中使用HTTP :: Cookie传递Cookie值

我能够在不需要登录数据的页面上成功完成此操作。我正在使用HTML :: Parser类。

LWP :: UserAgent提供了cookie_jar方法,通过从文件加载cookie来设置cookie。不过,我想在脚本本身中对cookie值进行编码。那可能吗?我在网上找不到任何工作示例。

这里是我的代码:

请原谅失踪“我”在一些地方变量声明。我急着写这段代码,试图理解LWP :: UserAgent中的Cookie处理的概念。

#!/usr/bin/perl 

use strict; 
use warnings; 
use HTTP::Request::Common; 
use LWP::UserAgent; 
use HTTP::Response; 
use HTTP::Cookies; 

package IdentityParse; 
use base "HTML::Parser"; 

my $title_flag=0; 
my $title=""; 

my $cookie_jar= HTTP::Cookies->new; 
$cookie_jar->clear; 
$cookie_jar->set_cookie(Name=Value); #Example, PHPSESSID=710c7aa60aa5cacdc40028ef79de24b2 

sub text{ 
my($self,$text)[email protected]_; 
if($title_flag) 
{ 
    $title.=$text; 
} 
} 

sub start{ 
my($self,$tag,$attr,$attrseq,$origtext)[email protected]_; 
if($tag =~ /^title$/i) 
{ 
    $title_flag=1; 
} 
} 

sub end{ 
my($self,$tag,$origtext)[email protected]_; 
if($tag =~ /^title$/i) 
{ 
    $title_flag=0; 
} 
} 

my $url="http://sitename.com/users/index.php"; 

my $ua= LWP::UserAgent->new(); 
$ua->agent('NeonFlash'); 
$ua->timeout(30); 
$ua->cookie_jar($cookie_jar); 

my $req= HTTP::Request->new(GET => $url); 
my $res= ($ua->request($req))->content; 

my $p = new IdentityParse; 
$p->parse($res); 

$p->eof; 

print "The title of the web page is: ".$title."\n"; 

摘要:

我使用的HTML解析器::类解析HTTP响应HTML页面。为了读取标签之间的值,我重写了HTML :: Parser的方法,开始,文本和结尾。

Cookie值以Key和Value形式传递。我知道,虽然我没有自己尝试过,但可以从文本文件加载cookie。但我想知道我们是否也可以这样做。

谢谢。

回答

-1

对于这类任务,我更喜欢WWW::Mechanize模块。

+0

请提供关于如何执行此任务的示例。 –

0

这是HTTP ::饼干的源代码:: set_cookie

 
sub set_cookie 
{ 
    my $self = shift; 
    my($version, 
     $key, $val, $path, $domain, $port, 
     $path_spec, $secure, $maxage, $discard, $rest) = @_; 

    # path and key can not be empty (key can't start with '$') 
    return $self if !defined($path) || $path !~ m,^/, || 
       !defined($key) || $key =~ m,^\$,; 

    # ensure legal port 
    if (defined $port) { 
    return $self unless $port =~ /^_?\d+(?:,\d+)*$/; 
    } 

看来,如果你想设置cookie来cookie_jar一样,你必须传递数组,而不是“”“key=value” ''
或者您也可以使用LWP :: UserAgent :: default_header来设置请求Cookie。
因为HTTP cookie是

的一部分