Perl 自动化之网页处理 WordPress 自动登陆查看

转载本站文章请注明,转载自:扶凯[http://www.php-oa.com]

本文链接:http://www.php-oa.com/2011/06/09/perl-web-lwp-cookie-wordpress-auto.html

自动化处理,和互联网上应用最多的都是基于 HTTP 协议的,原来我使用 Perl 处理,一直感觉有点乱,后来发现其实很简单
第一步:简单了触一下 LWP::UserAgent 模块的基本方法
第二步:在了解一下下面这几个部件就行了HTTP::Request, HTTP::Response,HTTP::Headers,HTTP::Cookies
第三步: 给网页的内容取出来,发现 Perl 中的模块超级给力.使用 Web::Scraper 吧,不二的选择.

下面是我以前写的一个例子,就是自动登陆到我的 Blog 中取出最新的评论来的小例子.大家可以基于这个写一个命令行写 Blog 的小软件.


#!/usr/bin/perl
use strict;
use warnings;
 
use HTTP::Request;
use HTTP::Cookies;
 
use LWP::UserAgent;
use Web::Scraper;
 
my $url         = 'http://www.php-oa.com/wp-login.php';
 
# 用来存 cookie
my $cookie_jar  = HTTP::Cookies->new(
        file        => "./cookies.lwp",
        autosave    => 1,
        );  
 
# 给处理 cookie 的对象放到 LWP::UserAgent 中来处理 cookie
# 登陆中
my $ua      = LWP::UserAgent->new;
my $cookies = $ua->cookie_jar($cookie_jar);
$ua->agent('Mozilla/6 [cn] (Ubuntu; Linux)');
my $res     = $ua->post( $url,
        [
            log     => 'admin',
            pwd    => 'passwd',
            'wp-submit' => 'Log In',
        ],
    );  
 
# 根据重定向的地址,给原来的 cookie 拿上
my $redirect_to = $res->header('location');
my $req         = HTTP::Request->new(GET=>$redirect_to);
$cookie_jar->add_cookie_header($req);
my $new_res     = $ua->request($req);
 
# 处理返回的结果 Response 取出自己要的内容
my $scraper = scraper {
    process '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div/div/div[2]/div[2]/div/div/div/blockquote/p','comment[]' => 'TEXT';
};
my $result = $scraper->scrape( $new_res->content );
 
# 输出结果
my @comments = @{ $result->{comment} };
for ( 0 .. $#comments ) {
    print "$_.  $comments[$_]\n";
}



Web::Scraper 非常推荐,详细的使用,可以看我以前的文章:

[Perl]网页分析处理的极品模块Web::Scraper

建议大家学习参考:http://www.perl.com/pub/2002/08/20/perlandlwp.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值