PerlでWebデータを取得し、任意のデータを抽出
正規表現難しい
こればっかりはなかなか理解できない
やること
とあるサイトのHTMLを抽出して表示
HTMLを抽出→タグを抽出→指定のタグを抽出→不要なタグを除去などして対応する。
実装
#!/usr/bin/env perl use strict; use warnings; use LWP::UserAgent; my $ua = LWP::UserAgent->new; $ua->timeout(10); $ua->env_proxy; my $url = "とあるサイトのURLです。適当に入れても動かないかも"; my $response = $ua->get($url); # 取得チェック if($response->is_success){ # 成功 my $text = $response->content; # rankのテーブルを抽出 if($text =~ /<table class=mainRankCC>(.+?)<\/table>/s){ # 指定のエリアを取得 my $tableText = $1; # 行の部分を取得 while($tableText =~ /<tr(.+?)>(.+?)<\/tr>/sg){ # print "----------start\n"; # print $2; # print "----------end\n"; # data my $trText = $2; my $data1 = ""; my $data2 = ""; if($trText =~ /<td class(.+?)>(.+?)<\/td>/s){ $data1 = $2; $data1 =~ s/<.*?>//g; } if($trText =~ /<a(.+?)>(.+?)<\/a>/s){ $data2 =$2; } # ランクを取得 my $rank = $data1.":".$data2; $rank =~ s/<.*?>//g; $rank =~ s/\n//g; print $rank."\n"; } }else{ print "not match"; } }else{ # 失敗 die $response->status_line; }
結果
[vagrant@localhost ~]$ perl sample.pl 1:steal 2:amazing 3:アメイジング 4:重篤 5:index 6:trough 7:confirm 8:bracket 9:commit 10:appreciate 11:present 12:issue 13:provide 14:concern 15:apply 16:reference 17:assume 18:undefined 19:description 20:available 21:consider 22:legend 23:expect 24:describe 25:indicate 26:while 27:leave 28:implement 29:単語 30:further 31:property 32:application 33:even 34:appropriate 35:imaginary 36:直接 37:involve 38:feature 39:improve 40:identify 41:remain 42:cause 43:procedure 44:save one's ass 45:deny 46:relevant 47:state 48:represent 49:due to 50:require [vagrant@localhost ~]$
複数行モードとか忘れていました
最初全然取得できないから疑問に思っていたら改行とか含まれたりすると動かなかったので改行を意識する?モードで対応
参考
まとめ
1つにまとめるのも多分できそうな感じはするけど、きちんと理解しないとあとで修正できないので分かる範囲に限定することにする。
これでとあるサイトのスクレイピングとか出来そう。