Get html from a site with ruby โ€‹โ€‹on rails

How to get page data from another website somewhere on the Internet with rubies on rails?

+5
source share
4 answers

You can use httparty to just get the data

Sample code (from example ):

require File.join(dir, 'httparty')
require 'pp'

class Google
  include HTTParty
  format :html
end

# google.com redirects to www.google.com so this is live test for redirection
pp Google.get('http://google.com')

puts '', '*'*70, ''

# check that ssl is requesting right
pp Google.get('https://www.google.com')

Nokogiri really excels at analyzing this data. Here is a sample code from Railscast :

url = "http://www.walmart.com/search/search-ng.do?search_constraint=0&ic=48_0&search_query=batman&Find.x=0&Find.y=0&Find=Find"
doc = Nokogiri::HTML(open(url))
puts doc.at_css("title").text
doc.css(".item").each do |item|
  title = item.at_css(".prodLink").text
  price = item.at_css(".PriceCompare .BodyS, .PriceXLBold").text[/\$[0-9\.]+/]
  puts "#{title} - #{price}"
  puts item.at_css(".prodLink")[:href]
end
+6
source

Use Net/HTTP(e.g. read this cheat sheet ):

require "net/https"

http = Net::HTTP.new "google.com", 80
request = Net::HTTP::Get.new "/"
response = http.request request

puts response.code
puts response.body
+5
source

Net:: HTTP , , , , rest-client:

RestClient.get('http://example.com/resource', params: {x: "1", y: "2"})
+3

OpenURI , .

require 'open-uri' , open('http://domain.tld/document.html').read.

+3
source

All Articles