Last active
June 5, 2021 15:30
-
-
Save smallmake/f3d71d6769cbf09179b86d1f0ddbdba0 to your computer and use it in GitHub Desktop.
国会図書館検索API利用サンプル
This file contains 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
require "faraday" | |
require 'nokogiri' | |
class NdlSearch | |
def get_book_info(title, creator = nil) | |
data = [] | |
query = { | |
:mediatype => 1, | |
:cnt => 10 | |
} | |
query[:title] = title | |
query[:creator] = creator if creator | |
response = ndl_get('/api/opensearch', query) | |
xml = Nokogiri::XML(response.body) | |
xml.remove_namespaces! | |
items = xml.xpath('/rss/channel/item') | |
items.each do |item| | |
#puts "-------" | |
#puts item | |
book = {} | |
item.children.each do |c| | |
key = c.name | |
next if key == 'text' | |
val = "#{c.content}" | |
label = c.attribute("type") | |
if label | |
label = "#{label}".gsub(/^dcndl:|^dcterms:/,'') | |
book[label] ||= [] | |
book[label] << val unless book[label].include?(val) | |
val = "#{label}:#{val}" | |
end | |
book[key] ||= [] | |
book[key] << val unless book[key].include?(val) | |
end | |
book = book.map {|key,val| [key, val.join(',')]}.to_h | |
data << book | |
end | |
data | |
end | |
private | |
def ndl_get(path, pram) | |
con = Faraday.new(:url => 'http://iss.ndl.go.jp') do |f| | |
f.request :url_encoded | |
f.response :logger | |
f.adapter Faraday.default_adapter | |
end | |
con.get path, pram | |
end | |
end | |
ndl_search = NdlSearch.new | |
res = ndl_search.get_book_info('オリジン','ダンブラウン') | |
res.each do |book| | |
puts '-----------' | |
book.each do |key, val| | |
puts "#{key}:#{val}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment