一旦遇到异常,是否可以忽略下面的所有行并转到for循环中的另一项?

时间:2019-04-16 18:50:48

标签: python exception

我正在尝试使用两个Google API调用来获取餐厅的price_level和电话号码。

首先,遍历

for restaurant in name:
    find_place_url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?"

    # use separate parameter dictionary b.c. findplace and findplacedetail have diff field.
    find_place_param ={}
    find_place_param["input"] = restaurant
    find_place_param["inputtype"] = "textquery"
    find_place_param["key"] = google_key

    # get place_id then use it to get phone number
    a = requests.get(find_place_url, parameters).json()

这是第一个findplace api,用于获取给定餐厅的place_id。它看起来像:

{'candidates': [{'place_id': 'ChIJdTDCTdT4cUgRqxush2XhgnQ'}], 'status': 'OK'}

如果给定的餐厅有适当的place_id,否则它将给出:

{'candidates': [], 'status': 'ZERO_RESULTS'}

现在这是我所有的代码:在这里,我抓住了place_id并尝试了一下,但因为如上所述,状态为零或确定,所以除外。但是,即使我通过,它也会运行find_place_detail api调用,而这需要place_id,因此它会失败。如果没有收到place_id,如何跳过最后的代码块?

price_level2 = []
phone_number = []
for restaurant in name:
    find_place_url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?"

    # use separate parameter dictionary b.c. findplace and findplacedetail have diff field.
    find_place_param ={}
    find_place_param["input"] = restaurant
    find_place_param["inputtype"] = "textquery"
    find_place_param["key"] = google_key

    # get place_id then use it to get phone number
    a = requests.get(find_place_url, parameters).json()
    print(a)
    # adding it to original parameter. since only this and findplace parameter has to be different.
    try:
        parameters["place_id"] = a["candidates"][0]["place_id"]
    except:
        print("Phone number not available")
        phone_number.append(None)

    # passing in fields of our interest
    parameters["fields"] = "name,price_level,formatted_phone_number"
    find_place_detail_url ="https://maps.googleapis.com/maps/api/place/details/json?"
    b = requests.get(find_place_detail_url, parameters).json()
    phone_number.append(b["result"]["formatted_phone_number"])
    price_level2.append(b["result"]['price_level'])

1 个答案:

答案 0 :(得分:1)

您可以使用else子句:

try:
    parameters["place_id"] = a["candidates"][0]["place_id"]
except KeyError:
    print("Phone number not available")
    phone_number.append(None)
else:
    parameters["fields"] = "name,price_level,formatted_phone_number"
    find_place_detail_url ="https://maps.googleapis.com/maps/api/place/details/json?"
    b = requests.get(find_place_detail_url, parameters).json()
    ...

另外,您的except子句应该更具体(我想您要抓住的情况是KeyError)。有关Python中异常处理的更多信息,请参见the documentation