我正在尝试使用Python GeoIP使用Maxmind数据库将IP地址转换为Geo详细信息。
import urllib2
import csv
import geoip2.database
db = geoip2.database.Reader("GeoLite2-City.mmdb")
target_url="http://myip/all.txt"
data = urllib2.urlopen(target_url)
for line in data:
response = db.city(line.strip())
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
我收到错误消息“ geoip2.errors.AddressNotFoundError:地址103.229.234.197不在数据库中。”
Traceback (most recent call last):
File "script.py", line 14, in <module>
response = db.city(line.strip())
File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 110, in city
return self._model_for(geoip2.models.City, 'City', ip_address)
File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 180, in _model_for
record = self._get(types, ip_address)
File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 176, in _get
"The address %s is not in the database." % ip_address)
geoip2.errors.AddressNotFoundError: The address 103.229.234.197 is not in the database.
Maxmind db提到的地址不在数据库中。但是它不会伤害我,但是如何忽略此错误并获得我可用的输出呢?
尝试除任何错误(尽管这不是最佳方法)之外,还希望获得特定的AddressNotFoundError。
try:
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
except:
pass
还,
try:
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
except AddressNotFoundError:
pass
仍然没有运气。
有什么建议么。
这里的问题是db.city调用中发生的异常,而不是值打印中发生的异常,因此您可以尝试以下操作:
import urllib2
import csv
import geoip2.database
db = geoip2.database.Reader("GeoLite2-City.mmdb")
target_url="http://myip/all.txt"
data = urllib2.urlopen(target_url)
for line in data:
try:
response = db.city(line.strip())
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
exception:
pass
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句