2015-11-05 41 views
-1

我正试图从提取房间价格和可用性数据,使用其API来自。然而,我遇到的问题是,当酒店在某一天没有空房时,会弹出错误消息。Python - 抓取结果与错误消息结束

基于下面的代码,当我使用Print JD的错误信息是:

{u'EanWsError': {u'category': u'SOLD_OUT', u'exceptionConditionId': -1, u'handling': u'RECOVERABLE', u'itineraryId': -1, u'ErrorAttributes': {u'errorAttributesMap': {u'entry': {u'value': 8001, u'key': u'SUPPLIER_ERROR_CODE'}}}, u'verboseMessage': u'errors.supplier.hotel.nolonger; error from supplier; 8001', u'presentationMessage': u'***The hotel you selected is no longer available. Please choose another.***'}, u'hotelId': 447643, u'customerSessionId': u'0AB2902D-92F0-CC91-50D2-6AA567897340', u'@size': u'0'} 

import urllib2 
import requests 
import md5 
import time 
import datetime 
import json 
import csv 
from datetime import date 
from datetime import timedelta 

#GENERATING SPECIAL KEYS FOR URL (GET) 
apiKey = 'xxxxxxxxxxxxxxx' #private keys, can't disclose 
secret = 'xxxxxxxxxxxxxxx' #private keys, can't disclose 
cid = 'xxxxxxxxxxxxxxx' #private keys, can't disclose 

hash = md5.new() 
timestamp = str(int(time.time())) 
sig = md5.new(apiKey + secret + timestamp).hexdigest() 

#Date and Hotel Variables 
StartDate = '12/31/2015' 
EndDate = '12/31/2015' 
HotelIDs = '447643' 

url = 'http://api.ean.com/ean-services/rs/hotel/v3/avail?apiKey=' + apiKey + '&sig=' + sig + '&cid=' + cid + '&currencyCode=TWD&hotelId='+ HotelIDs + '&arrivalDate=' + StartDate + '&departureDate=' + EndDate + '&room1=1' 
res = requests.get(url) 
jd = json.loads(res.text)['HotelRoomAvailabilityResponse'] 

Name = jd['hotelName'] 

for Rooms in jd['HotelRoomResponse']: 
    Descp = Rooms['rateDescription'] 
    Avail = Rooms['currentAllotment'] 
    Rate = Rooms['RateInfo']['ChargeableRateInfo']['@nightlyRateTotal'] 

    print Name, Descp, Avail, Rate 

我怎样才能解决这个问题呢?

有没有一种更简单的方法来提取数据使用python,因为我认为我的方法实际上效率很低。

回答

0

也许我错过了一些东西,但我不确定你为什么在这里使用美丽的唇膏。您应该尝试切割出来,并使用如下所示的urllib2json

url = 'http://api.ean.com/ean-services/rs/hotel/v3/avail?apiKey=' + apiKey + '&sig=' + sig + '&cid=' + cid + '&currencyCode=TWD&hotelId='+ HotelIDs + '&arrivalDate=' + StartDate + '&departureDate=' + EndDate + '&room1=1' 
jd = json.load(urllib2.urlopen(url)) 

那么对于错误处理,我只想使用一些try模块,如:

try: 
    Name = jd['hotelName'] 

    for Rooms in jd['HotelRoomResponse']: 
      Descp = Rooms['rateDescription'] 
      Avail = Rooms['currentAllotment'] 
      Rate = Rooms['RateInfo']['ChargeableRateInfo']['@nightlyRateTotal'] 

      print Name, Descp, Avail, Rate 
except: 
    try: 
      Error = jd['hotelId'] 
      print "Error with " + Error 
    except: 
      print "unknown Error"