dou*_*oug 35
Hostip.info是一个开源项目,其目标是构建/维护将IP地址映射到城市的数据库.他们的 about页面解释了依赖于填充此数据库的数据源.
使用HostIP,有两种方法可以从IP地址获取位置数据:
它们还有一个设计良好且易于使用的RESTFUL API:只需在GET请求字符串中的i***p =***之后传入您的IP地址):
import urllib
response = urllib.urlopen('http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true').read()
print(response)
Run Code Online (Sandbox Code Playgroud)
其次,项目网站还可以下载完整的数据库.
luc*_*luc 13
它不是Python库.但是http://ipinfodb.com/提供了一个web服务,可以通过urllib轻松地用Python代码包装.
http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=74.125.45.100
http://api.ipinfodb.com/v3/ip-country/?key=<your_api_key>&ip=74.125.45.100
Run Code Online (Sandbox Code Playgroud)
您需要申请免费的API密钥.有关详细信息,请参阅API文档.
我在另一个被埋没的问题中发布了这个问题,但链接在这里:
#!/usr/bin/env python
from urllib2 import urlopen
from contextlib import closing
import json
# Automatically geolocate the connecting IP
url = 'http://freegeoip.net/json/'
try:
with closing(urlopen(url)) as response:
location = json.loads(response.read())
print(location)
location_city = location['city']
location_state = location['region_name']
location_country = location['country_name']
location_zip = location['zipcode']
except:
print("Location could not be determined automatically")
Run Code Online (Sandbox Code Playgroud)
将HTTP GET请求发送到:freegeoip.net/{format}/ {ip_or_hostname}以接收Python可以解析的JSON输出.
我得到以下JSON密钥,这应该足以满足您的需求:
找到https://freegeoip.net/ ; 下面的python示例.
import requests
FREEGEOPIP_URL = 'http://freegeoip.net/json/'
SAMPLE_RESPONSE = """{
"ip":"108.46.131.77",
"country_code":"US",
"country_name":"United States",
"region_code":"NY",
"region_name":"New York",
"city":"Brooklyn",
"zip_code":"11249",
"time_zone":"America/New_York",
"latitude":40.645,
"longitude":-73.945,
"metro_code":501
}"""
def get_geolocation_for_ip(ip):
url = '{}/{}'.format(FREEGEOPIP_URL, ip)
response = requests.get(url)
response.raise_for_status()
return response.json()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46440 次 |
| 最近记录: |