Created
August 29, 2012 05:05
-
-
Save makevoid/3507024 to your computer and use it in GitHub Desktop.
Simple scraper example ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # simple scrape example with mechanize | |
| # | |
| # setup: gem install mechanize | |
| require 'mechanize' | |
| agent = Mechanize.new | |
| agent.user_agent = "Mac Firefox" | |
| host = "http://livescore.com/soccer/italy" | |
| page = agent.get host | |
| results = page.search("table table td[width='468'] tr").select do |tr| | |
| tr["bgcolor"] && ["#333333", "#cfcfcf", "#dfdfdf"].include?(tr["bgcolor"]) | |
| end | |
| games = [] | |
| last_date, last_title = nil | |
| results.each do |tr| | |
| tds = tr.search("td") | |
| if tr["bgcolor"] == "#333333" | |
| if tds[1] && tds[1].inner_text.strip | |
| date = tds[1].inner_text.strip | |
| puts "[#{date}]" | |
| last_date = date | |
| else # title | |
| title = tds[0].inner_text.strip | |
| puts "-"*50 | |
| puts "> #{title}" | |
| last_title = title | |
| end | |
| else # game | |
| puts tds.map{ |td| td.inner_text.strip }.join ", " | |
| games << { | |
| type: tds[0].inner_text.strip, | |
| team_a: tds[1].inner_text.strip, | |
| team_b: tds[3].inner_text.strip, | |
| result: tds[2].inner_text.strip, | |
| title: last_title, | |
| date: last_date | |
| } | |
| end | |
| end | |
| puts "\n\nGames: " | |
| p games |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment