Python geoip使用json查找国家/地区

时间:2016-04-24 09:50:43

标签: python location geoip

from urllib2 import urlopen
from contextlib import closing
import json
import time
import os

while True:
    url = 'http://freegeoip.net/json/'
    try:
        with closing(urlopen(url)) as response:
            location = json.loads(response.read())
            location_city = location['city']
            location_state = location['region_name']
            location_country = location['country_name']
            #print(location_country)
            if location_country == "Germany":
                print("You are now surfing from: " + location_country)
                os.system(r'firefox /home/user/Documents/alert.html')
                    except:
        print("Could not find location, searching again...")
    time.sleep(1)   

它没有回复任何国家我可以帮助解决问题吗?

2 个答案:

答案 0 :(得分:0)

除了错误的缩进外,您的代码看起来还不错。

问题似乎是页面本身没有响应。例如,如果您尝试在浏览器中打开它,则会拒绝连接。

可能api要么过载,要么不再存在。

答案 1 :(得分:0)

首先,服务器似乎是down

您可能已经注意到了这一点,但裸except隐藏了这一事实。通常,您不应该捕获所有异常,但应该捕获您期望的异常 - 在这种情况下,urllib2.URLError异常似乎是合适的:

import urllib2

url = 'http://freegeoip.net/json/'
try:
    response = urllib2.urlopen(url)
    ...
except urllib2.URLError as exc:
    print('Could not find location due to exception: {}'.format(exc))

如果您运行上面的代码,您可能会看到此输出:

Could not find location due to exception: <urlopen error [Errno 101] Network is unreachable>

服务器可能早先出现,问题可能实际上有不同的原因,例如: json.loads()可能会失败。如果您更改了上面显示的异常处理程序,您将能够看到它失败的位置。