是否有任何代码段或示例可以帮助我从IP地址获取国家/地区?首先,我需要获取用户的IP,然后根据我需要获取国家/地区。以下是我正在尝试并开始使用的代码段。
from geoip import geolite2
match = geolite2.lookup('17.0.0.1')
我正在尝试安装geoip包但它会让我失误。
In [1]: from geoip import geolite2
In [2]: match = geolite2.lookup('17.0.0.1')
-----------------------------------------------------------
TypeError Traceback (most recent call last)
/mnt/c/u/for_penguins/topenguins/helpers.py in <module>()
----> 1 match = geolite2.lookup('17.0.0.1')
/mnt/c/u/for_penguins/lib/python3.6/site-packages/geoip.py in lookup(self, ip_addr)
362
363 def lookup(self, ip_addr):
--> 364 return self._get_actual_db().lookup(ip_addr)
365
366 def __repr__(self):
/mnt/c/u/for_penguins/lib/python3.6/site-packages/geoip.py in _get_actual_db(self)
348 if self._db is not None:
349 return self._db
--> 350 rv = self._load_database()
351 self._db = rv
352 return rv
/mnt/c/u/for_penguins/lib/python3.6/site-packages/geoip.py in _load_database(self)
340 msg += ' It\'s provided by PyPI package "%s"' % self.pypi_name
341 raise RuntimeError(msg)
--> 342 return mod.loader(self, sys.modules[__name__])
343
344 def _get_actual_db(self):
/mnt/c/u/for_penguins/lib/python3.6/site-packages/_geoip_geolite2/__init__.py in loader(dat
7 def loader(database, mod):
8 filename = os.path.join(os.path.dirname(__file__), database_name)
----> 9 return mod.open_database(filename)
/mnt/c/u/for_penguins/lib/python3.6/site-packages/geoip.py in open_database(filename)
506 with open(filename, 'rb') as f:
507 buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
--> 508 md = _read_mmdb_metadata(buf)
509 return MaxMindDatabase(filename, buf, md)
/mnt/c/u/for_penguins/lib/python3.6/site-packages/geoip.py in _read_mmdb_metadata(buf)
380 """Reads metadata from a given memory mapped buffer."""
381 offset = buf.rfind(MMDB_METADATA_START,
--> 382 buf.size() - MMDB_METADATA_BLOCK_MAX_SIZE)
383 if offset < 0:
384 raise ValueError('Could not find metadata')
TypeError: a bytes-like object is required, not 'str'
仅供参考,我使用的是python 3.6.3
答案 0 :(得分:0)
也安装数据库:pip install python-geoip-geolite2