天天看點

Perl結合飛信發送免費的天氣預報資訊

每天在公司上班,打開QQ的同時,就順便看了一下今天的天氣情況。當時就在想,可不可以用perl來解析這個html頁面,抽取其中必要的elements,然後透過第三方的飛信将該消息發送給自己,不就可以了麼。說幹就幹,就寫了這麼一段代碼,算法不是特别好,參考了某位網友的處理方法,但又有差別。

擷取天氣預報的頁面位址,我用了這個address

http://qq.ip138.com/weather/zhejiang/HangZhou.htm 

完整的code如下:(調試了一天,媽媽的)

#!/usr/bin/perl -w 

use strict;

#utf8一定要加,否則出現亂碼

use utf8; 

use LWP::Simple; 

use 5.010;

my $url = shift || "http://qq.ip138.com/weather/zhejiang/HangZhou.htm"; 

my $content = get $url; 

my @url = split /\n/,$content; 

my $path = "/root/lib"; 

my $fetion = "/root/lib/fetion"; 

&get_weather(\@url); 

system(qq{LD_LIBRARY_PATH=$path $fetion --mobile=12345678901 --pwd='123456' --to=123456 --exit-on-verifycode=1 --file-utf8=/root/weather.txt --msg-type=1}); 

sub get_weather($) { 

    my ( $weather ) = @_; 

    my ( $count,$i ) = ( 0,0 ); 

    while ( $i < scalar(@$weather) ) { 

           next unless @$weather[$i++] =~ /日期/; 

           $i += 1; 

           open my $file,'>>','/root/weather.txt' or die "$!\n"; 

           if ( -s '/root/weather.txt' > 0 ) { 

               system("cat /dev/null >/root/weather.txt"); 

           } 

           while ( $count < 1 ) { 

                  @$weather[$i++] =~ /(?:.*)\>(?<name1>.*?)\<\/td\>/; 

                  $count ++; 

                  say $file "$+{name1}\t"; 

           say $file "\n"; 

           $i += 9; 

$count = 0; 

                  @$weather[$i++] =~ /.*\>(?<name2>.*)\<\/td\>/; 

                  say $file "$+{name2}\t"; 

          say $file "\n"; 

           $count = 0; 

                  @$weather[$i++] =~ /(?:.*)\>(?<name3>.*?)\<\/td\>/; 

                  say $file "$+{name3}\t"; 

    close $file; 

    last; 

    } 

此支perl程式,僅僅抽取了天氣預報詳情頁面的這幾個值:

1) 日期

2) 實際天氣情況

3)當天的氣溫

其他的就沒有弄了,情況類似。

附:linux下配置飛信的方法

下載下傳機器人支援庫

http://www.it-adv.net/fetion/linuxso_20101113.rar

注:我的系統是64位的,但是如果下載下傳了64位的版本,ms有問題,32位的就OK

另外,linux使用者,請不要把支援庫中的 lib* 複制到 /usr/lib 下,因為發行版本不同,可能會覆寫您機器中的核心庫,導緻嚴重系統問題。您可以把庫解壓到主程式的相同目錄,然後以 LD_LIBRARY_PATH=. ./fetion 來運作)

詳細介紹見這個頁面

http://bbs.it-adv.net/viewthread.php?tid=1081&extra=page%3D1

本文轉自dongfang_09859 51CTO部落格,原文連結:http://blog.51cto.com/hellosa/620743,如需轉載請自行聯系原作者

繼續閱讀