Skip to main content

用Perl来自动抓取及存档目标网页

技术
Author

cookwhy

Published

September 2, 2008

最近因为工作需要,一直要监视几个网页,如果有更新,就要对它们进行一些处理。每天不停地刷网页,太无聊太痛苦了,于是用Perl写了一个自动监视网页并提取相关信息的东西。

首先,要装上LWP::UserAgent和HTML::Manipulator这两个Perl模块。整体思路是用LWP::UserAgent模块读取特定网页下来,然后再用HTML::Manipulator来对保存下来的html进行操作,分离出你想要的部分。

  1. 用LWP::UserAgent来操作网页十分简单,基本上以下几个步骤就搞定了:

use LWP::UserAgent;
$ua = LWP::UserAgent->new;
\(ua->agent(“MyApp/0.1 “); print “Please input the url you want to save:\n”; chomp(\)url = );

# Create a request
my $req = HTTP::Request->new(POST => $url);
$req->content_type(‘application/x-www-form-urlencoded’);
$req->content(‘query=libwww-perl&mode=dist’);

# Pass request to the user agent and get a response back
my $res = \(ua->request(\)req);

# Check the outcome of the response
if ($res->is_success) {
#do whatever you want to do here
}
else {
print $res->status_line, “”;
}

  1. 读取了网页后,就可以用HTML::Manipulator的HTML::Manipulator::extract_title把该网页的标题读出来,用HTML::Manipulator::extract_content把你关心的某一部分内容读取出来,例如:

my \(title = HTML::Manipulator::extract_title(\)res->content);
my \(content = HTML::Manipulator::extract_content(\)res->content, ‘articleBody’);

就是读取html里id为articleBody部分的内容。

我在写我的程序的时候,还用了delHtml函数来对读取出来的内容进行了进一步的格式化,把里面多余的html代码去掉了。如里需要程序自动判断网页是否从特定时间开始有无更新,则需要用上LWP::UserAgent的if-modified-since了。