我正在尝试使用 Google API 和 json 信息从查询中获取地址信息。但是我只得到最终商品的地址,而不是汇总的地址。如何在 python 中解决此问题?
我的代码由3部分组成: 1.从json文件(sample.json)中提取纬度和经度信息。 2.使用Google API查询地址 3.从查询结果中提取地址(json格式)并写入文件(test.csv)
首先,我的输入json文件(sample.json)如下:
{"last_updated":1554148141,
"ttl":10,
"data":{"stations":
[{"station_id":"1","external_id":"0b0fda98-08f3-11e7-a1cb-3863bb33a4e4","name":"Métro Champ-de-Mars (Viger / Sanguinet)","short_name":"6001","lat":45.51035067563653,"lon":-73.55650842189789,"rental_methods":["CREDITCARD","KEY"],"capacity":33,"electric_bike_surcharge_waiver":false,"eightd_has_key_dispenser":false,"has_kiosk":true},
{"station_id":"2","external_id":"0b0fdf05-08f3-11e7-a1cb-3863bb33a4e4","name":"Ste-Catherine / Dezery","short_name":"6002","lat":45.539385081961676,"lon":-73.54099988937377,"rental_methods":["CREDITCARD","KEY"],"capacity":19,"electric_bike_surcharge_waiver":false,"eightd_has_key_dispenser":false,"has_kiosk":true},
{"station_id":"3","external_id":"0b0fe114-08f3-11e7-a1cb-3863bb33a4e4","name":"Clark / Evans","short_name":"6003","lat":45.51100666600306,"lon":-73.56760203838348,"rental_methods":["CREDITCARD","KEY"],"capacity":19,"electric_bike_surcharge_waiver":false,"eightd_has_key_dispenser":false,"has_kiosk":true}
] } }
接下来是我在python中的代码: (API_KEY是我的个人密钥,因此标记为“ ****”。)
import json
import requests
import csv
input_json = json.load(open('sample.json'))
for i in input_json ['data']['stations']:
lat = i['lat']
lon = i['lon']
API_URL = "https://maps.googleapis.com/maps/api/geocode/json?latlng={},{}&formatted_address&result_type=street_address&key=".format(
lat, lon)
API_KEY = '***********'
try:
response = requests.get(API_URL+API_KEY, auth=('user','pass'))
data = response.json()
address = []
for i in data['results']:
a = i['formatted_address']
address.append(a)
f = csv.writer(open('test.csv', 'w'))
f.writerow(address)
except Exception as e:
print(e)
else:
print(address)
运行此代码时,结果如下:
['2025 Rue Clark, Montréal, QC H2X 2R6, Canada', '2026 Rue Clark, Montréal, QC H2X 1Y8, Canada']
根据Google查询,结果应显示总共6个地址(每个项目2个地址)。 我的结果仅显示最后一项的2个地址。
我不知道如何适当地编码循环部分。您能帮我解决这个问题吗?