2017-10-12 55 views
3

我試圖使用事件API來獲取有關兩個日期之間只有音樂事件(音樂會)的信息。例如,我想獲得每場音樂會以下信息從20171012到20171013:從請求到事件API獲取一個空陣列

- city 
- performer 
- country 
- latitude 
- longitude 
- genre 
- title 
- image 
- StarTime 

即時通訊使用Python的例子可在網上,並改變它來獲得上述數據。但現在它不能正常工作我只是能夠得到這個信息:

{'latitude': '40.4', 
    'longitude': '-3.68333', 
    'start_time': '2017-10-12 20:00:00', 
    'city_name': 'Madrid', 'title': 'Kim Waters & Maysa Smooth en Hot Jazz Festival'} 

但是表演者,流派國家和圖像url它不工作。你知道如何獲得這些信息嗎?當我改變下面的python例子來獲取這些信息時,它總是返回一個空數組。

蟒蛇例如工作:(但是,沒有得到表演,流派,國家和圖像的URL,如果我theese元素添加到event_features我得到一個空數組)

import requests 
    import datetime 

def get_event(user_key, event_location , start_date, end_date, event_features, fname): 

    data_lst = [] # output 
    start_year = int(start_date[0:4]) 
    start_month = int(start_date[4:6]) 
    start_day = int(start_date[6:]) 

    end_year = int(end_date[0:4]) 
    end_month = int(end_date[4:6]) 
    end_day = int(end_date[6:]) 

    start_date = datetime.date(start_year, start_month, start_day) 
    end_date = datetime.date(end_year, end_month, end_day) 
    step = datetime.timedelta(days=1) 

    while start_date <= end_date: 

     date = str(start_date.year) 
     if start_date.month < 10: 
      date += '0' + str(start_date.month) 
     else: 
      date += str(start_date.month) 

     if start_date.day < 10: 
      date += '0' + str(start_date.day) 
     else: 
      date += str(start_date.day) 
     date += "00" 
     date += "-" + date 

     url = "http://api.eventful.com/json/events/search?" 
     url += "&app_key=" + user_key 
     url += "&location=" + event_location 
     url += "&date=" + date 
     url += "&page_size=250" 
     url += "&sort_order=popularity" 
     url += "&sort_direction=descending" 
     url += "&q=music" 
     url+= "&c=music" 

     data = requests.get(url).json() 

     try: 
      for i in range(len(data["events"]["event"])): 
       data_dict = {} 
       for feature in event_features: 
        data_dict[feature] = data["events"]["event"][i][feature] 
       data_lst.append(data_dict) 
     except: 
      pass 

     print(data_lst) 
     start_date += step 


def main(): 

    user_key = "" 
    event_location = "Madrid" 
    start_date = "20171012" 
    end_date = "20171013" 
    event_location = event_location.replace("-", " ") 
    start_date = start_date 
    end_date = end_date 
    event_features = ["latitude", "longitude", "start_time"] 
    event_features += ["city_name", "title"] 
    event_fname = "events.csv" 

    get_event(user_key, event_location, start_date, end_date, event_features, event_fname) 


if __name__ == '__main__': 
    main() 
+1

您的'event_features'列表只包含這五個元素。 –

+0

謝謝你的回答。我只是把這5個元素放在一起,因爲就像它的工作一樣。例如,如果我添加執行者,它將返回一個空數組。 – JonD

回答

1

如果你看一下由eventful.com返回的數據,幾件事情是清楚的:

  1. 對於國家,進行應用的領域是COUNTRY_NAME。這從您的「event_features」列表中缺失
  2. 每個事件可能有多個執行者。要獲得所有表演者,您需要在「event_features」列表中添加「表演者」
  3. 沒有名爲類型的字段,因此您無法找到類型
  4. 「圖片」字段始終爲「無」。這意味着沒有可用的圖像。

這是修改後的代碼。希望它效果更好,它會幫助你前進。

import datetime 
import requests 

data_lst = [] # output 
event_features = ["latitude", "longitude", "start_time", "city_name", 
        "country_name", "title", "image", "performers"] 

def get_event(user_key, event_location, start_date, end_date): 

    start_year = int(start_date[0:4]) 
    start_month = int(start_date[4:6]) 
    start_day = int(start_date[6:]) 

    end_year = int(end_date[0:4]) 
    end_month = int(end_date[4:6]) 
    end_day = int(end_date[6:]) 

    start_date = datetime.date(start_year, start_month, start_day) 
    end_date = datetime.date(end_year, end_month, end_day) 
    step = datetime.timedelta(days=1) 

    while start_date <= end_date: 

     date = str(start_date.year) 
     if start_date.month < 10: 
      date += '0' + str(start_date.month) 
     else: 
      date += str(start_date.month) 

     if start_date.day < 10: 
      date += '0' + str(start_date.day) 
     else: 
      date += str(start_date.day) 
     date += "00" 
     date += "-" + date 

     url = "http://api.eventful.com/json/events/search?" 
     url += "&app_key=" + user_key 
     url += "&location=" + event_location 
     url += "&date=" + date 
     url += "&page_size=250" 
     url += "&sort_order=popularity" 
     url += "&sort_direction=descending" 
     url += "&q=music" 
     url += "&c=music" 

     data = requests.get(url).json() 
     print "==== Data Returned by eventful.com ====\n", data 

     try: 
      for i in range(len(data["events"]["event"])): 
       data_dict = {} 
       for feature in event_features: 
        data_dict[feature] = data["events"]["event"][i][feature] 
       data_lst.append(data_dict) 
     except IndexError: 
      pass 

     print "====================================" 
     print data_lst 
     start_date += step 


def main(): 

    user_key = "Enter Your Key Here" 
    event_location = "Madrid" 
    start_date = "20171012" 
    end_date = "20171013" 
    event_location = event_location.replace("-", " ") 
    start_date = start_date 
    end_date = end_date 
    #event_fname = "events.csv" 

    get_event(user_key, event_location, start_date, end_date) 


if __name__ == '__main__': 
    main() 
3

你應該調試你的問題, 不要忽略所有例外

替換用線try: ... except: pass

data = requests.get(url).json() 
    if "event" in data.get("event", {}): 
     for row in data["events"]["event"]: 
      # print(row) # you can look here what are the available data, while debugging 
      data_dict = {feature: row[feature] for feature in features} 
      data_lst.append(data_dict) 
    else: 
     pass # a problem - you can do something here 

你會看到一個KeyError與丟失feature未出現在「行」的名稱。您應該修復缺失的功能並閱讀關於該服務的API的文檔。與「city_name」類似,國家/地區特徵可能是「country_name」。也許你應該設置「include」參數來指定更多的搜索細節部分,而不僅僅是默認值。


的普遍try: ... except: pass不應該使用,因爲「錯誤不應該無聲地傳遞。」 (The Zen of Python

Handling Exceptions

...除了子句可以省略異常名(一個或多個)最後,作爲通配符。請謹慎使用此功能,因爲以這種方式很容易掩蓋真正的編程錯誤! ...

可能出現意想不到的例外的更重要的命令是requests.get(url).json(),例如, TimeoutException異常。無論如何,如果出現問題,你不應該繼續「while」循環。

+0

感謝您的解釋。但在文件中出現國家如此肩負的工作。 – JonD

+0

當某些功能丟失而不是錯誤時,使用'row.get(feature)'獲取'None'。 – Javier

+0

@Javier我同意這樣做對生產有好處,但是在開發開始時,即使上游API還沒有實現,最好是修正列名中的拼寫錯誤,並考慮哪些列有時可能會丟失,以便除了空字符串之外,最終還沒有一個未被注意的字符串「無」。 – hynekcer

1

我能夠成功從performer,imagecountry字段的Eventful API中提取數據。但是,我不認爲事件搜索API支持genre - 我沒有看到它in their documentation。我想添加"country_name", "country_abbr"到你的event_features數組中。這增加了這些值所得到的JSON:

'country_abbr': u'ESP', 
'country_name': u'Spain' 

Performer也可以通過添加到"performers"event_features被檢索。這將增加該給JSON輸出:

'performers': { 
    u'performer': { 
     u'name': u'Kim Waters', 
     u'creator': u'evdb', 
     u'url': u'http://concerts.eventful.com/Kim-Waters?utm_source=apis&utm_medium=apim&utm_campaign=apic', 
     u'linker': u'evdb', 
     u'short_bio': u'Easy Listening/Electronic/Jazz', u'id': u'P0-001-000333271-4' 
    } 
} 

要檢索圖像,添加imageevent_features陣列。請注意,並非所有事件都有圖像。你要麼看到'image': None

'image': { 
    u'medium': { 
     u'url': u'http://d1marr3m5x4iac.cloudfront.net/store/skin/no_image/categories/128x128/other.jpg', 
     u'width': u'128', 
     u'height': u'128' 
    }, 
    u'thumb': { 
     u'url': u'http://d1marr3m5x4iac.cloudfront.net/store/skin/no_image/categories/48x48/other.jpg', 
     u'width': u'48', 
     u'height': u'48' 
    } 
} 

祝你好運! :)