2016-09-14 4 views
1

Maxmind Databaseを使用して、Python GeoIPを使用してIPアドレスをGeoの詳細に変換しようとしています。Python GeoIP2 AddressNotFoundError

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 

運。

提案があります。

答えて

2

ここでの問題は、例外ではない値の印刷で、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 
関連する問題