Python GeoIP2 地址未找到错误

标签 python exception geoip maxmind

我正在尝试使用 Python GeoIP 使用 Maxmind 数据库将 IP 地址转换为地理详细信息。

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

关于Python GeoIP2 地址未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39485054/

相关文章:

python - 一个简单的 GUI 应用程序中有多少个线程?

nginx - 更新 GeoIP.dat 时 nginx 重新加载是否足够

geoip - Maxminds GeoIP2 与 GeoLite2 相比在每月的第一个星期二的准确度如何?

Logstash/Kibana GeoIP 不工作

python - 检查一个值是否是列表的第一次出现并在 Python 中标记为 1

javascript - 抛出 JavaScript 异常的标准做法是什么?

android - IntentService 启动期间出现 java.lang.NullPointerException

python - SSL ConnectionResetError 从哪里来?

python - python请求的理想 block 大小

python - 如何在 Python 2.x 中对对象执行自省(introspection)?