2016-04-24 46 views
0
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) 

它不回答任何国家我可以得到帮助解决问题吗?Python geoip找到使用json的国家

+0

您的除外是缩进错误。它应该只有4个空格 – tobspr

回答

0

除了错误的缩进,你的代码看起来很好。

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

可能是API被重载或不再存在。

+0

tnx,你知道任何其他类似的服务吗? – Stevie

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()可能会失败。如果您更改上面显示的异常处理程序,您将能够看到它失败的位置。