首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python GeoIP2 AddressNotFoundError

Python GeoIP2 AddressNotFoundError
EN

Stack Overflow用户
提问于 2016-09-14 07:44:24
回答 1查看 3.8K关注 0票数 2

我试图使用Python GeoIP将IP地址转换为Geo详细信息,使用Maxmind数据库。

代码语言:javascript
复制
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不在数据库中。“

代码语言:javascript
复制
    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。

代码语言:javascript
复制
try:
     print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
except:
       pass

还有,

代码语言:javascript
复制
try:
     print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude

except AddressNotFoundError:
     pass

还是没有运气。

任何建议。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-14 09:54:30

这里的问题是在db.city调用中发生的异常,而不是在值打印中发生的异常,因此您可以尝试这样做:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39485054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档