首页 > 解决方案 > 一旦遇到异常,我可以忽略下面的所有行并转到 for 循环中的另一个项目吗?

问题描述

我正在尝试使用两个 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()

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

{'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'])

标签: pythonexception

解决方案


您可以使用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子句应该更具体(我想您要抓住的情况是 a KeyError)。有关 Python 中异常处理的更多信息,请参阅文档


推荐阅读