Python|python ip转地址;Python IP to GEO
例一: 使用geoip2库来实现
具体使用如下:
注意需要下载GeoLite2-City.mmdb库到本地。
下载==>http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
geoip2返回的具体信息可以先打印出来,格式稍有差异需要
什么再调整地址的获取方式。
这种方式大多情况都可以拿到一个大致地址。如果是国内IP建议结合百度地图实现,如例二。
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import sys
import geoip2.database
import requests
import json
reload(sys)
sys.setdefaultencoding('utf8')
try:
# 这里注意文件路径
reader = geoip2.database.Reader('./GeoLite2-City_20191224/GeoLite2-City.mmdb')
ip = sys.argv[1]
#print "" % ip
response = reader.city(ip)
country = response.country.names['zh-CN'] if response.country.names.has_key('zh-CN') else " "
city = response.city.names['zh-CN'] if response.city.names.has_key('zh-CN') else " "
country_name = country.encode("UTF_8")
print (country+" "+city).encode("UTF-8")
except Exception as e:
print e
print " "
例二: 调用百度地图开放平台的接口,来获取国内IP的详细地址。目前可以得到如下信息:
{
"address": "CN|北京|北京|None|ALIBABA|0|0",
"content": {
"address_detail": {
"province": "北京市",
"city": "北京市",
"district": "",
"street": "",
"street_number": "",
"city_code": 131
},
"address": "北京市",
"point": {
"y": "4825007.72",
"x": "12950160.97"
}
},
"status": 0
}
代码:
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import sys
import geoip2.database
import requests
import json
reload(sys)
sys.setdefaultencoding('utf8')
try:
reader = geoip2.database.Reader('./GeoLite2-City_20191224/GeoLite2-City.mmdb')
ip = sys.argv[1]
response = reader.city(ip)
country = response.country.names['zh-CN'] if response.country.names.has_key('zh-CN') else " "
city = response.city.names['zh-CN'] if response.city.names.has_key('zh-CN') else " "
country_name = country.encode("UTF_8")
if country_name == '中国':
result = requests.get("http://api.map.baidu.com/location/ip?ip="+ip+"&ak=GbR1YfmFzR**************pyIxkvG&coor%20=%20bd09ll")
if result.status_code == 200:
result = json.loads(result.content)
address = result["content"]["address"]
print address
else:
print "中国"
else:
print (country+" "+city).encode("UTF-8")
except Exception as e:
print e
print " "
【Python|python ip转地址;Python IP to GEO】百度地图开放平台的信息,还有api文档点这里http://lbsyun.baidu.com/
ak是在平台上生成的KEY,免费。
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- 流转
- 一起来学习C语言的字符串转换函数
- python自定义封装带颜色的logging模块
- 【58】转移注意力
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- 考前焦虑——接纳情绪,转移注意力
- leetcode|leetcode 92. 反转链表 II
- 视频转换器哪种好用()