Python中使用pygeoip库通过IP获取经纬度并集成到百度地图显示时,创建对象遇到问题,如何解决?
import pygeoip
gi = pygeoip.GeoIP(‘GeoLiteCity.dat’)
response = gi.record_by_addr(ip)
我正常导入库,路径也正确,想要用 Python 的 pygeoip 库通过 ip 获取经纬,然后给百度地图,在页面显示,结果在形成对象这儿卡住了
各位大佬,帮吗看一下是啥情况?
分割线
File “/usr/local/lib/python2.7/site-packages/pygeoip/init.py”, line 118, in init
self._fp = codecs.open(filename, ‘rb’, ENCODING)
File “/usr/local/lib/python2.7/codecs.py”, line 896, in open
------------if mode[:1] not in set(‘rwa’):
--------------mode = ‘r’ + mode
Open an interactive python shell in this frame if ‘b’ not in mode:
------------# Force opening of the file in binary mode
------------mode = mode + ‘b’
----file = builtin.open(filename, mode, buffering) # 报这个错误!!!
----if encoding is None:
--------return file
----info = lookup(encoding)
----srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
----# Add attributes to simplify introspection
IOError: [Errno 2] No such file or directory: 'GeoLiteCity.dat’
Python中使用pygeoip库通过IP获取经纬度并集成到百度地图显示时,创建对象遇到问题,如何解决?
No such file or directory: ‘GeoLiteCity.dat’
遇到 pygeoip 创建对象的问题,通常是数据库文件路径不对或文件损坏。先确保你下载了正确的 GeoLiteCity.dat 或 GeoIP.dat 文件,并放在代码能访问的位置。
最常见的问题是文件路径不对。试试用绝对路径,或者把 .dat 文件放在项目根目录下。这里给你个完整的代码示例,从查经纬度到在百度地图显示都包了:
import pygeoip
import webbrowser
import os
# 1. 初始化 GeoIP 对象 - 关键步骤
# 确保 GeoLiteCity.dat 文件路径正确
geoip_db_path = 'GeoLiteCity.dat' # 如果文件在当前目录
# 或者用绝对路径:geoip_db_path = '/path/to/your/GeoLiteCity.dat'
if not os.path.exists(geoip_db_path):
print(f"错误:找不到数据库文件 {geoip_db_path}")
print("请从 MaxMind 下载 GeoLiteCity.dat 并放在正确位置")
exit(1)
try:
gi = pygeoip.GeoIP(geoip_db_path, pygeoip.MEMORY_CACHE)
print("GeoIP 对象创建成功!")
except Exception as e:
print(f"创建 GeoIP 对象失败: {e}")
exit(1)
# 2. 通过 IP 获取地理位置
ip_address = '8.8.8.8' # 示例 IP,可以换成你要查的 IP
try:
record = gi.record_by_addr(ip_address)
if record:
latitude = record.get('latitude')
longitude = record.get('longitude')
city = record.get('city', '未知城市')
country = record.get('country_name', '未知国家')
print(f"IP: {ip_address}")
print(f"位置: {country}, {city}")
print(f"经纬度: {latitude}, {longitude}")
else:
print(f"未找到 IP {ip_address} 的地理位置信息")
exit(1)
except Exception as e:
print(f"查询 IP 失败: {e}")
exit(1)
# 3. 生成百度地图 HTML
html_content = f'''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>IP地理位置显示</title>
<style>
#map {{ height: 600px; width: 100%; }}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=你的百度地图AK"></script>
<script>
// 用获取到的经纬度
var latitude = {latitude};
var longitude = {longitude};
// 初始化地图
var map = new BMap.Map("map");
var point = new BMap.Point(longitude, latitude);
map.centerAndZoom(point, 15);
map.enableScrollWheelZoom(true);
// 添加标记
var marker = new BMap.Marker(point);
map.addOverlay(marker);
// 信息窗口
var infoWindow = new BMap.InfoWindow(
"IP: {ip_address}<br/>位置: {city}, {country}<br/>经纬度: {latitude}, {longitude}"
);
marker.addEventListener("click", function() {{
this.openInfoWindow(infoWindow);
}});
</script>
</body>
</html>
'''
# 4. 保存并打开地图
html_file = 'ip_location_map.html'
with open(html_file, 'w', encoding='utf-8') as f:
f.write(html_content)
print(f"\n地图已生成: {html_file}")
webbrowser.open(f'file://{os.path.abspath(html_file)}')
注意两个关键点:
- 把代码里的
你的百度地图AK换成你在百度地图开放平台申请的密钥 - 确保
GeoLiteCity.dat文件路径正确
如果还报错,可能是 pygeoip 库版本问题。这个库有点老了,如果实在搞不定,可以考虑用 geoip2 库替代,它维护得更好。
总结:检查数据库文件路径,确保文件完整。
文件我直接放在同级目录下了,文件路径没问题,刚刚在项目外面试了一下{‘city’: u’Shenzhen’, ‘region_code’: u’30’, ‘area_code’: 0, ‘time_zone’: ‘Asia/Chongqing’, ‘dma_code’: 0, ‘metro_code’: None, ‘country_code3’: ‘CHN’, ‘latitude’: 22.533299999999997, ‘postal_code’: None, ‘longitude’: 114.13330000000002, ‘country_code’: ‘CN’, ‘country_name’: ‘China’, ‘continent’: ‘AS’}
很 ok !项目内就是不行。。。。
使用绝对路径吧。
有可能你的 Python 运行路径与文件路径不一致,而你又使用的是相对路径
print(os.getcwd())
self._fp = codecs.open(filename, ‘rb’, ENCODING)
您瞧瞧打印的当前路径对不对
托您的福,用 print os.path.realpath(file)
print ‘*’ * 50 方法调好了路径


