python - 一旦遇到异常,我可以忽略下面的所有行并转到 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'])
解决方案
您可以使用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 中异常处理的更多信息,请参阅文档。
推荐阅读
- css - 在滚动上制作相对 div 剪辑静态徽标 - CSS
- javascript - 单击模态按钮时未提交表单
- c++ - QLineEdit 绘制与实际文本不同的文本(text() 非空的占位符)
- python - 如何将 django 默认 ForeignKey 类型从整数更改为字符串?
- angular - 我可以在我的应用程序完成后将其前端更改为 Angular 吗?
- c# - 具有唯一 ID 的逻辑错误
- python - 使用气流 MySqlOperator 时插入查询中的语法错误
- c# - asp.net core 2.0 Entity Framework 如何访问用户配置文件
- java - 我如何使用 Java 解决 CPLEX:不可行行 'c2': 0 = -3
- python - 在 numpy.insert 命令中插入值的顺序是什么?