当我运行附加到CSV的此代码时,URL位于columnA [1]和 在A [2]处插入名称会出现以下错误:
IndexError:列表索引超出范围
目标是通过以CSV格式提供名称来提取位置。
# importing the requests library
import requests
import csv
# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"
f = open("z1.csv")
reader = csv.DictReader(f)
for row in reader:
print(row["URL"])
# location given here
location = row["URL"]
records = location.splitlines()
myreader = csv.reader(records)
for row in myreader:
print('Location', row[0])
# Defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}
# Sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)
# Extracting data in json format
data = r.json()
# Extracting latitude, longitude and formatted address
# of the first matching location
latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']
# Printing the output
print("Latitude:%s\nLongitude:%s\nFormatted Address:%s"
%(latitude, longitude,formatted_address))
答案 0 :(得分:0)
在访问第一个元素之前,您必须确保列表data['results']
不为空。如果它是一个空数组,那么它将引发异常IndexError : List index Out of range
还有一条建议,您需要确保字段results
中存在字段data
。否则,对data["results"]
的调用将引发KeyError
例外。在你的测试中并非如此。但使用get
函数而不是括号dict.get(key) instead of dict[key]
通常是一种很好的做法。
您的代码的修复程序是:
# importing the requests library
import requests
import csv
# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"
f = open("z1.csv")
reader = csv.DictReader(f)
for row in reader:
print(row["URL"])
# location given here
location = row["URL"]
records = location.splitlines()
myreader = csv.reader(records)
for row in myreader:
print('Location', row[0])
# Defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}
# Sending get request and saving the response as response object
# Make sure that you had a successful request
r = requests.get(url = URL, params = PARAMS)
if r.status_code == 200:
# Extracting data in json format
data = r.json()
if data.get("results", []):
# Extracting latitude, longitude and formatted address
# of the first matching location
latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']
# Printing the output
print("Latitude:%s\nLongitude:%s\nFormatted Address:%s"
%(latitude, longitude,formatted_address))