Python网络分析项目中GeoIP Webservice无数据返回求助
问题描述
我正在用Python开发一个网络分析小型项目,希望获取从traceroute命令收集的一系列IP地址的地理定位数据。目前我使用GeoIP API,代码如下:
with geoip2.webservice.Client(self.accountID, self.licenseKey, host='geolite.info') as client: for address in self.uniqueIPs: city = client.city('139.222.0.1') crds = [city.location.latitude, city.location.longitude] self.geolocations.append(crds)
当前遇到问题:打印city、crds或geolocations时无任何输出;打印address时仅第一个地址会输出,移除API代码后才能打印全部地址。查阅文档未得到有效帮助,请问我哪里操作有误?
问题分析与解决
- 硬编码IP地址:代码中调用
client.city()时固定传入'139.222.0.1',而非循环变量address,导致所有循环都查询同一个IP,若该IP查询失败会直接中断流程。 - 未处理异常:GeoIP API调用可能抛出异常(网络错误、无效IP、权限不足等),一旦第一个IP查询触发异常,循环会直接终止,这就是仅输出第一个
address的原因——后续循环未执行。
修正后的代码示例:
import geoip2.errors with geoip2.webservice.Client(self.accountID, self.licenseKey, host='geolite.info') as client: for address in self.uniqueIPs: print(address) # 打印当前循环的IP,确认遍历正常 try: # 替换硬编码IP为循环变量address city = client.city(address) # 检查坐标是否有效 if city.location.latitude is not None and city.location.longitude is not None: crds = [city.location.latitude, city.location.longitude] self.geolocations.append(crds) print(f"定位结果:{crds}") else: print(f"未获取到{address}的有效坐标") except geoip2.errors.AddressNotFoundError: print(f"{address}不在GeoIP数据库中") except Exception as e: print(f"查询{address}时出错:{str(e)}")
额外检查项:
- 确认
self.accountID和self.licenseKey有效,且具备GeoLite API的访问权限 - 核实
self.uniqueIPs列表包含多个有效的公网IP地址 - 确保本地网络可正常访问
geolite.info服务
内容的提问来源于stack exchange,提问作者sunny
相关产品推荐
相关产品推荐

