[ruby on rails]做网络爬虫或json与string互转

gem rest-client可以让我们用 Ruby 发送 HTTP 请求
在irb中:

require 'rest-client'
response = RestClient.get "http://www.weather.com.cn/weather1d/101010100.shtml"
response.body
require 'nokogiri'
doc = Nokogiri::HTML.parse(response.body)
doc.css(".today .tem").map{ |x| x.text }  # 得到 ["\n13°C\n", "\n2°C\n", "\n"] 
doc.css(".today .tem").text #得到 "\n4°C\n\n9°C\n\n" 

json和string

require 'json'
{ :id => 123, :name => "foobar" }.to_json       # => "{\"id\":123,\"name\":\"foobar\"}"
JSON.parse( "{\"id\":123,\"name\":\"foobar\"}" )   # => {"id"=>123, "name"=>"foobar"}

猜你喜欢

转载自blog.csdn.net/qq_41037744/article/details/88859104
今日推荐