且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Perl结合飞信发送免费的天气预报信息

更新时间:2022-09-27 14:09:50

每天在公司上班,打开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

本文转自dongfang_09859 51CTO博客,原文链接:http://blog.51cto.com/hellosa/620743,如需转载请自行联系原作者