最近工作开始忙起来了,也不看天气预报了.直到今天下雨把我淋透了..看来,天气预报还是很重要的.所以写了个小脚本获取 www.ip138.com 接口上的天气预报.通过139邮箱发送到手机端.代码如下:
- #!/usr/bin/perl
- use warnings;
- use strict;
- use LWP::UserAgent;
- use HTML::TreeBuilder;
- use Net::SMTP;
- use Net::SMTP_auth;
- use MIME::Base64;
- #my $wday= (localtime(time()))[6];
- my $i = '2';
- my $j = '3';
- my $weather_url = "http://qq.ip138.com/weather/beijing/HaiDian.htm";
- my $cont = get_html($weather_url,"Accept-language" => "zh-cn", 'Accept-Charset' => 'gb2312');
- my $table = $1 if $cont =~ m/<p align="center"><table width="700" borderColorDark="#ffffff" borderColorLight="#008000" bor
- der="1" cellspacing="0" cellpadding="1" align="center">(.*?)<\/p>/s;
- my $tree = HTML::TreeBuilder->new();
- $tree->parse($table);
- $tree->eof();
- # print $tree->dump;
- my @th = $tree->find_by_tag_name("th");
- my @tr = $tree->find_by_tag_name("td");
- my $tomorrow = $th[$i]->as_text()." ". $tr[$i]->as_text()." ".$tr[$i+8]->as_text()." ".$tr[$i+16]->as_text();
- my $after_day = $th[$j]->as_text()." ". $tr[$j]->as_text()." ".$tr[$j+8]->as_text()." ".$tr[$j+16]->as_text();
- $tree->delete();
- send_mail("$tomorrow","$after_day");
- =pod
- foreach my $row($tree->find_by_tag_name("tr")){
- foreach my $cell($row->content_list){
- print $cell->as_text."\t";
- }
- print "\n";
- }
- =cut
- sub get_html {
- my $url = shift;
- my $browser= LWP::UserAgent->new();
- $browser->agent("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;SV1;)");
- my $resp = $browser->get($url);
- return unless $resp->is_success;
- return $resp->content;
- }
- sub send_mail {
- my $data1 = shift;
- my $data2 = shift;
- my $smtp_mail_host = 'smtp.sinanet.com';
- my $mail_user_from = 'donghui@leju.sina.com.cn';
- my $mail_user_to = 'yisildeai@139.com';
- my $mail_user_pass = "P@ssW0rd";
- my $mail_hello = 'mail.sinanet.com';
- my $smtp = Net::SMTP->new(
- Host => "$smtp_mail_host",
- Hello => "$mail_hello",
- timeout => 40,
- Debug => 1,)or die "can not connect mail server!\n";
- $smtp->auth("$mail_user_from","$mail_user_pass")or die "auth faild!\n";
- $smtp->mail("$mail_user_from");
- $smtp->to("$mail_user_to");
- $smtp->data();
- $smtp->datasend("From: donghui <donghui\@leju.sina.com.cn>\n");
- $smtp->datasend("To: <donghui\@.leju.sina.com.cn>\n");
- $smtp->datasend("Subject: <天气预报>\n");
- $smtp->datasend("Content-Type: text/plain;charset=\"gb2312\"\n");
- $smtp->datasend("Content-Transfer-Encoding: base64\n");
- $smtp->datasend(encode_base64("Dear: \n"));
- $smtp->datasend(encode_base64(" $data1\n $data2\n"));
- # $smtp->datasend(encode_base64(" The day after torrow: $data2\n"));
- $smtp->datasend(encode_base64("------------\n"));
- $smtp->datasend(encode_base64("Evil\' ^_^"));
- $smtp->datasend("\n\n");
- $smtp->dataend();
- $smtp->quit();
- }
效果如下:
当然了,你的手机也会定时收到.不过前提你的SIM卡类型为China_mobile.
再定义一个crond任务 每天晚上8点定时发送.
00 20 */1 * * /usr/bin/perl /usr/local/share/info/get_weather.pl
#service crond restart
#chkconfig crond on
大功告成..起码每个月省了两块钱的天气预报短信.呵呵....