2016-09-14 220 views
1

我試圖使用Python GeoIP將IP地址轉換爲使用Maxmind數據庫的地理詳細信息。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