2017-04-02 56 views
-2

欲隔離pageInfo - 爲了>使用totalResults檢查,如果鏈路是有效的(= 1)如何檢查是否一個YouTube ID是與Nokogori和Rails有效

這是video_controller.rb:

submitted_link = "https://www.googleapis.com/youtube/v3/videos?part=id&id="[email protected][:id]+"&key="+ENV["KEY_YOUTUBE"] 
link_result = Nokogiri::HTML(open(submitted_link)) 

我得到這樣的結果:

{ 
"kind": "youtube#videoListResponse", 
"etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/GWU- 
KIYwNWh_dAkOcA5xDaFhS48\"", 
"pageInfo": { 
    "totalResults": 1, 
    "resultsPerPage": 1 
}, 
"items": [ 
{ 
    "kind": "youtube#video", 
    "etag": "\"uQc- 
    MPTsstrHkQcRXL3IWLmeNsM/wp71OkMYYohvwOjzLL_4NN8r7w0\"", 
    "id": "m9h7qCdgPN4" 
    } 
] 
} 

你有一個想法?

+1

你嘗試過這麼遠嗎? – Iceman

+1

嘗試使用'HTTParty'或'RestClient'而不是'nokogiri'。你可以得到json,你會得到結果爲json並解析它。像'link_result [「pageInfo」] [「totalResults」] == 1' –

+0

非常感謝你:) 通過做:youtube_link = JSON.parse(response)['pageInfo'] ['totalResults']它工作得很好。 – Matt

回答

0

這不是Nokogiri的任務,因爲Nokogiri是解析HTML或XML的。該文件的開頭爲:

引入nokogiri解析並非常迅速地搜索XML/HTML,也有正確 實現CSS3選擇器的支持以及支持XPath 1.0。

相反,您的輸出是JSON,需要由JSON類進行解析。 這是未經測試的代碼,但在球場:

require 'open-uri' 
require 'json' 

foo = JSON[open("https://www.googleapis.com/youtube/v3/videos?part=id&id=#{@results[:id]}&key=#{ENV['KEY_YOUTUBE']}").read] 

解析一次,你會回到Ruby對象,在這種情況下,哈希值。默想這一點:

require 'json' 

str = DATA.read 
foo = JSON[str] 
# => {"kind"=>"youtube#videoListResponse", 
#  "etag"=>"\"uQc-MPTsstrHkQcRXL3IWLmeNsM/GWU-KIYwNWh_dAkOcA5xDaFhS48\"", 
#  "pageInfo"=>{"totalResults"=>1, "resultsPerPage"=>1}, 
#  "items"=> 
#  [{"kind"=>"youtube#video", 
#  "etag"=>"\"uQc-MPTsstrHkQcRXL3IWLmeNsM/wp71OkMYYohvwOjzLL_4NN8r7w0\"", 
#  "id"=>"m9h7qCdgPN4"}]} 

foo['pageInfo']['totalResults'] # => 1 

__END__ 
{ 
"kind": "youtube#videoListResponse", 
"etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/GWU-KIYwNWh_dAkOcA5xDaFhS48\"", 
"pageInfo": { 
    "totalResults": 1, 
    "resultsPerPage": 1 
}, 
"items": [ 
{ 
    "kind": "youtube#video", 
    "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/wp71OkMYYohvwOjzLL_4NN8r7w0\"", 
    "id": "m9h7qCdgPN4" 
    } 
] 
}