【Ruby】4gifsのRSS取得、gifのURLを取り出す
(11/4)
うーんこれだと取得したgifは動かないものですね。
きちんと動いているgifが欲しいならば、きちんと個別記事にアクセスしないとなのかなあ?
RSS取得して、パースして・・・というところはすんなりだったんですけど、gifのURLだけ取り出したくて・・・
先にコードを載せますと
require 'rss' rss = RSS::Parser.parse('http://forgifs.com/gallery/srss/7') rss.items.each do |item| puts item.title desc = item.description if md = desc.match(%r!src="(.+?)"!) puts md[1] else puts "No match data" end end
4gifsのRSSはこんなんなっとります。
<category>photo</category> <pubDate>Tue, 21 Oct 2014 11:35:04 -0400</pubDate> </item> <item> <title> <![CDATA[ Ping-pong-cucumber-trick-shot ]]> </title> <link> http://forgifs.com/gallery/v/Cool/Ping-pong-cucumber-trick-shot.gif.html </link> <guid isPermaLink="false"> http://forgifs.com/gallery/v/Cool/Ping-pong-cucumber-trick-shot.gif.html </guid> <description> <![CDATA[ <a href="http://forgifs.com/gallery/v/Cool/Ping-pong-cucumber-trick-shot.gif.html"><img border="0" src="http://forgifs.com/gallery/d/221175-2/Ping-pong-cucumber-trick-shot.gif" width="150" height="112"/></a><br/>Ping pong ball flying at high speed breaks the end of a cucumber<br/>In album <a href="http://forgifs.com/gallery/v/Cool/">Cool GIFs</a> ]]> </description> <author>Gallery Administrator</author> <category>photo</category> <pubDate>Tue, 21 Oct 2014 10:05:44 -0400</pubDate> </item> (以下略)
descriptionはいろいろ出てきますが、要はsrc=
で始まって、""で囲われている部分だけ取り出せば良いと。
%rは直後に来る文字を正規表現のデリミタとするので(でないとエスケープしまくるハメになる)
%r{src="(.+?)"}
デリミタにする文字はなんでも良いそうなので
%r!src="(.+?)"!
これでも良いと。
で、MatchDataオブジェクトが帰ってくるので[]メソッドでマッチした部分を取り出す。
Sneaky-stalking-dachshund-puppy http://forgifs.com/gallery/d/221178-2/Sneaky-stalking-dachshund-puppy.gif Ping-pong-cucumber-trick-shot http://forgifs.com/gallery/d/221175-2/Ping-pong-cucumber-trick-shot.gif Ice-cream-sandwich-prank http://forgifs.com/gallery/d/221172-2/Ice-cream-sandwich-prank.gif Kiss-cam-breakup http://forgifs.com/gallery/d/221156-2/Kiss-cam-breakup.gif Boop-turns-off-kitten http://forgifs.com/gallery/d/221154-2/Boop-turns-off-kitten.gif Dog-sniffing-sits-on-kittens-head http://forgifs.com/gallery/d/221151-2/Dog-sniffing-sits-on-kittens-head.gif Leaves-surprise-ball-prank http://forgifs.com/gallery/d/221148-2/Leaves-surprise-ball-prank.gif Truck-spanking-show-off http://forgifs.com/gallery/d/221123-2/Truck-spanking-show-off.gif Angry-dog-bites-camera http://forgifs.com/gallery/d/221121-2/Angry-dog-bites-camera.gif Condom-car-window http://forgifs.com/gallery/d/221117-2/Condom-car-window.gif
記事のタイトルとそこにあるgifのURLを表示できると。
gifが複数あったら? と思ったけど、とりあえず各記事一つずつしかないのでこれでいいかなと(いいのかなあ?)
参考記事:
Rubyで「正規表現でマッチした部分を抽出する」を書いたのだが、なんかしょぼかったので復習 - maeharinの日記
rubyでRSS情報を取得 (自分用のRSS reader作成に向けて) | rakkyooの備忘録(RSSの取得について)
throw Life - はてブRSSの要素を取得するRubyプログラム(RSSの要素取得について)
http://www.lightship.co.jp/FileVisor6/help/operation/regexp.htm(正規表現について)