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

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

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

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

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

  1. #!/usr/bin/perl -w 
  2.  
  3. use strict;
  4. #utf8一定要加,否則出現亂碼
  5. use utf8; 
  6. use LWP::Simple; 
  7. use 5.010;
  8.  
  9. my $url = shift || "http://qq.ip138.com/weather/zhejiang/HangZhou.htm"; 
  10. my $content = get $url; 
  11. my @url = split /\n/,$content; 
  12. my $path = "/root/lib"
  13. my $fetion = "/root/lib/fetion"
  14.  
  15. &get_weather(\@url); 
  16. 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}); 
  17.  
  18. sub get_weather($) { 
  19.     my ( $weather ) = @_; 
  20.     my ( $count,$i ) = ( 0,0 ); 
  21.  
  22.     while ( $i < scalar(@$weather) ) { 
  23.  
  24.            next unless @$weather[$i++] =~ /日期/; 
  25.            $i += 1; 
  26.  
  27.            open my $file,'>>','/root/weather.txt' or die "$!\n"; 
  28.            if ( -s '/root/weather.txt' > 0 ) { 
  29.                system("cat /dev/null >/root/weather.txt"); 
  30.            } 
  31.  
  32.            while ( $count < 1 ) { 
  33.                   @$weather[$i++] =~ /(?:.*)\>(?<name1>.*?)\<\/td\>/; 
  34.                   $count ++; 
  35.                   say $file "$+{name1}\t"; 
  36.            } 
  37.  
  38.            say $file "\n"; 
  39.            $i += 9; 
  40. $count = 0
  41.            while ( $count < 1 ) { 
  42.                   @$weather[$i++] =~ /.*\>(?<name2>.*)\<\/td\>/; 
  43.                   $count ++; 
  44.                   say $file "$+{name2}\t"; 
  45.            } 
  46.  
  47.           say $file "\n"; 
  48.            $i += 9; 
  49.            $count = 0
  50.            while ( $count < 1 ) { 
  51.                   @$weather[$i++] =~ /(?:.*)\>(?<name3>.*?)\<\/td\>/; 
  52.                   $count ++; 
  53.                   say $file "$+{name3}\t"; 
  54.            } 
  55.  
  56.     close $file; 
  57.     last; 
  58.  
  59.     } 

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

1) 日期

2) 實際天氣情況

3)當天的氣溫

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

附:linux下配置飛信的方法

下載機器人支持庫

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

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

另外,linux用戶,請不要把支持庫中的 lib* 複製到 /usr/lib 下,因爲發行版本不同,可能會覆蓋您機器中的核心庫,導致嚴重系統問題。您可以把庫解壓到主程序的相同目錄,然後以 LD_LIBRARY_PATH=. ./fetion 來運行)

詳細介紹見這個頁面

  1. http://bbs.it-adv.net/viewthread.php?tid=1081&extra=page%3D1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章