每天在公司上班,打開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;
- while ( $count < 1 ) {
- @$weather[$i++] =~ /.*\>(?<name2>.*)\<\/td\>/;
- $count ++;
- say $file "$+{name2}\t";
- }
- say $file "\n";
- $i += 9;
- $count = 0;
- while ( $count < 1 ) {
- @$weather[$i++] =~ /(?:.*)\>(?<name3>.*?)\<\/td\>/;
- $count ++;
- 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