Perl 自动化之网页处理 WordPress 自动登陆查看
转载本站文章请注明,转载自:扶凯
本文链接: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 (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/div/div/div/div/div/div/div/div/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 非常推荐,详细的使用,可以看我以前的文章:
网页分析处理的极品模块Web::Scraper
建议大家学习参考:http://www.perl.com/pub/2002/08/20/perlandlwp.html
页:
[1]