2010-09-04 22 views

Trả lời

6

Bạn có thể sử dụng httparty chỉ lấy dữ liệu

Mẫu mã (từ 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 thực sự xuất sắc trong việc phân tích dữ liệu mà .. Dưới đây là một số mã ví dụ từ 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 
5

Sử dụng Net/HTTP (ví dụ, đọc this cheatsheet):

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 
3

Net::HTTP tàu trong thư viện chuẩn, đó là một lợi thế, nhưng có mát thư viện cấp cao hơn bạn có thể có một cái nhìn tại, như rest-client:

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

Cảm ơn vì điều này. Nó chỉ có thể là tấm vé cho một dự án mới của tôi. –

3

Tôi thích OpenURI bản thân mình nếu nó chỉ đơn giản là có được nội dung không ồn ào.

Chỉ cần thêm require 'open-uri' vào môi trường và sau đó thực hiện open('http://domain.tld/document.html').read.

Các vấn đề liên quan