BLOG

 

235日のセブIT留学  成長日記「PythonからぐるなびAPIのデータを取得!」 ( 43/235 days )

20 8月 2018, Posted by keisuke in IT留学, プログラミング

こんばんわ!Keisukeです!

 

今回は, Pythonを用いてぐるなびAPIからデータを取得したいと思います!

 

公式サイトに既にPyhtonのテストコードがあったためそれを改良して使用しました!

 

改良した点

・urllibのインポート方法

・hit_per_pageの追加

・freewordの追加

・現在地の変更

 

検索内容

自宅から3km以内のカレーを取り扱うお店の表示!

※個人情報は”xxx”で隠してます!

 

以下コード

 

#!/usr/bin/env python

# -*- coding: utf-8 -*-

#*****************************************************************************************

# ぐるなびWebサービスのレストラン検索APIで緯度経度検索を実行しパースするプログラム

# 注意:ここでは緯度と経度の値は固定でいれています。

#    APIアクセスキーの値にはユーザ登録で取得したものを入れてください。

#*****************************************************************************************

import sys

import urllib.parse

import urllib.request

import json

####

# 変数の型が文字列かどうかチェック

####

def is_str( data = None ) :

 if isinstance( data, str) or isinstance(data, int) :

   return True

 else :

   return False

 

if __name__ == “__main__”:

 

   ####

   # 初期値設定

   ####

   # APIアクセスキー

   keyid     = “xxxxxxxxxxxxxx”

   # エンドポイントURL

   url      = “https://api.gnavi.co.jp/RestSearchAPI/20150630/”

   # 緯度・経度、範囲を変数に入れる

   # 緯度経度は日本測地系で日比谷シャンテのもの。範囲はrange=1で300m以内を指定している。

   # 緯度

   latitude  = “xxxxxxxxxxxxxxxxx”

   # 経度

   longitude = “xxxxxxxxxxxxxxxx”

   # 範囲

   # 1:300m、2:500m、3:1000m、4:2000m、5:3000m

   range     = “5”

   hit_per_page = “100”

   freeword = “カレー”

   ####

   # APIアクセス

   ####

   # URLに続けて入れるパラメータを組立

   query = [

   ( “format”,      “json” ),

   ( “keyid”,       keyid ),

   ( “latitude”,    latitude ),

   ( “longitude”,   longitude ),

   ( “range”,       range ),

   ( “hit_per_page”,hit_per_page),

   (“freeword”,  freeword )

   ]

 

   # URL生成

   url += “?{0}”.format( urllib.parse.urlencode( query ) )

   # API実行

   try :

       result = urllib.request.urlopen( url ).read()

   except ValueError :

       print(“1″,u”APIアクセスに失敗しました。”)

   #sys.exit()

   

   ####

   # 取得した結果を解析

   ####

   data = json.loads( result )

   #print(data)

   # エラーの場合

   if “error” in data :

       if “message” in data :

           print(u”{0}”.format( data[“message”] ))

       else :

           print(“2″,u”データ取得に失敗しました。”)

   #sys.exit()

   

   # ヒット件数取得

   total_hit_count = None

   if “total_hit_count” in data :

       total_hit_count = data[“total_hit_count”]

   

   # ヒット件数が0以下、または、ヒット件数がなかったら終了

   if total_hit_count is None or int(total_hit_count) <= 0 :

       print(“3″,u”指定した内容ではヒットしませんでした。”)

   #sys.exit()

   

   # レストランデータがなかったら終了

   if not “rest” in data :

       print(“4″,u”レストランデータが見つからなかったため終了します。”)

   #sys.exit()

   

   # ヒット件数表示

   print(“{0}件ヒットしました。”.format( total_hit_count ))

   print(“—-“)

   

   # 出力件数

   disp_count = 0

   # レストランデータ取得

   for rest in data[“rest”] :

       line             = []

       id             = “”

       name             = “”

       access_line          = “”

       access_station       = “”

       access_walk          = “”

       code_category_name_s = []

       # 店舗番号

       if “id” in rest and is_str( rest[“id”] ) :

           id = rest[“id”]

           line.append( id )

       # 店舗名

       if “name” in rest and is_str( rest[“name”] ) :

           name = u”{0}”.format( rest[“name”] )

           line.append( name )

       if “access” in rest :

           access = rest[“access”]

       # 最寄の路線

       if “line” in access and is_str( access[“line”] ) :

           access_line = u”{0}”.format( access[“line”] )

       # 最寄の駅

       if “station” in access and is_str( access[“station”] ) :

           access_station = u”{0}”.format( access[“station”] )

       # 最寄駅から店までの時間

       if “walk”    in access and is_str( access[“walk”] ) :

           access_walk = u”{0}分”.format( access[“walk”] )

       line.extend( [ access_line, access_station, access_walk ] )

 

       # 店舗の小業態

       if “code” in rest and “category_name_s” in rest[“code”] :

           for category_name_s in rest[“code”][“category_name_s”] :

               if is_str( category_name_s ) :

                   code_category_name_s.append( u”{0}”.format( category_name_s ) )

                   line.extend( code_category_name_s )

 

       # タブ区切りで出力

           print(“\t”.join( line ))

           disp_count += 1

   

   # 出力件数を表示して終了

   print(“—-“)

   print(“5″,u”{0}件出力しました。”.format( disp_count ))

   #sys.exit()

 

実行結果!

#——————————————————————————–

6件ヒットしました。

—-

6305459 レコレクト             スープカレー

5809331 松の実       和食 その他   和食 その他 欧米・各国料理 その他

6366802 磯はな       カフェ カフェ  ケーキ屋・スイーツ

5672457 和屋          居酒屋 居酒屋  和食 その他

h934315 丸亀製麺     讃岐うどん      讃岐うどん うどん

7500560 サワディ         タイカレー

—-

5 6件出力しました。

 

#——————————————————————————–

 

取得できましたね!

 

サンプルコードがあるので非常に簡単に取得できました!

ですが, 公式サイトそのままでは動かないので少しいじる必要があるようです!

Pyscriptからベタ打ちか呼び出せばすぐに使える?かも知れないです!

 

余談ですがレコレクトがすごくおいしんですよね~

 

[今日の達成]

・PyhonからぐるなびAPIを取得!

 

[今日の未消化]

・他のAPIデータを呼び出してみる

Post a comment