我循环遍历traceroute中的IP地址数量并从ip-api.com获取地理位置数据,然后我将已传回的数据添加到名为info的变量中。
def toKML(iplist,namelist):
kml = simplekml.Kml()
x = 0
for ip in iplist:
url =urllib2.Request('http://ip-api.com/json/' + str(ip)) #using API to gather geo info
info =json.load(urllib2.urlopen(url)) # setting data value to the feedback from the API for each IP
if 'city' in info:
print info['lon']
kml.newpoint(name=str(info['city']),coords=[str(info['lon']),str(info['lat'])],description=(namelist[x]))
x += 1
else:
print "Geo-locational data not found for the ip "+ ip +"."
x +=1
kml.save("test.kml")
API返回的JSON对象示例如下:
{"as":"AS15169 Google Inc.","city":"Mountain View","country":"United States","countryCode":"US","isp":"Google","lat":37.386,"lon":-122.0838,"org":"Google","query":"8.8.8.8","region":"CA","regionName":"California","status":"success","timezone":"America/Los_Angeles","zip":"94040"}
这会生成一个KML文档,但它没有正确解析坐标,这里是KML文档的一个部分:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<Document id="feat_1">
<Placemark id="feat_2">
<name/>
<Point id="geom_0">
<coordinates>-,0,. 5,1,.</coordinates>
</Point>
<description>sgyl-core-2b-ae7-717.network.virginmedia.net</description>
</Placemark>
JSON对象中的坐标是正确的,因为当我打印“&#39; lon”时,坐标是正确的。 &#39; info&#39;中的值返回:
-0.13 -0.0931 -0.0931 -0.13 -0.13 -0.13 -122.1826 -6.2597 -6.2597 -6.2597 -122.1822 -0.0931 -0.0931 -122.1822
错误位于代码中:
kml.newpoint(name=str(info['city']),coords=[str(info['lon']),str(info['lat'])],description=(namelist[x]))
非常感谢任何有关此事的帮助。
答案 0 :(得分:0)
好的,我认为我破译了代码的某些部分。你需要解决几件事:
==
是相等比较运算符。 =
是作业。data.insert(x,info); x += 1
将项目添加到列表中,而只使用data.append(info)
你读了json(它被解析成python字典)并将其存储到info
变量中:
info = json.load(urllib2.urlopen(url))
然后将其放入data
列表中。所以当你尝试做的时候:
city[counter] == str(data['city'])
(在==
与=
混淆之后),您尝试使用city
将列表counter
编入索引,这实际上是一个项目data
列表,这是一个字典,因此是错误。
但我怀疑会有很多其他错误,可能无法帮助你解决所有错误。
EDIT1:我曾试图估算代码的外观(但是 当然,我不确切地知道你想要什么......我猜,因为我不是 熟悉KML):
def toKML(iplist, namelist):
kml = simplekml.KML()
for ip, name in zip(iplist, namelist):
url = urllib2.Request('http://ip-api.com/json/' + str(ip))
info = json.load(urllib2.urlopen(url))
kml.newpoint(name=str(info['city']),
coords=[(str(info['lon']), str(info['lat']))],
description=name)
kml.save('test.kml') # don't know what this should do, but I'm guesing
# saving to a file?
注意:
str
- 从您向我们展示的内容来看,它似乎已经是所有字符串 编辑2 :至于您的坐标问题 - 我不知道您需要在coords
中确切地拥有什么,但如果您的json
看起来像是你说它看起来像,你正在通过:
coords=[("-122.0838", "37.386")]
到kml.newpoint
函数。我真的不知道这是否正确。您应该检查此函数中预期的格式并适当地转换数据。
另外 - 请勿使用x
索引namelist
- 这是不必要的,如果您不小心可能会导致问题 - 只需使用{{ 1}}正如我向您展示的那样(假设zip
和namelist
具有相同的长度)。如果你不知道iplist
做了什么 - 它需要两个列表,并在迭代时从列表中的相同位置获取变量。例如:
zip
它不仅更短,而且更不容易出错(你不必保留 追踪一些指数)。
最后 - 我真的非常非常地建议你阅读一些python教程并在尝试更复杂的事情之前在python中使用一些简单的问题。你学的越多,你对python的兴趣就越大,相反,我在这里看到了这种痛苦。祝你好运。