2016-04-24 85 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()可能會失敗。如果您更改上面顯示的異常處理程序,您將能夠看到它失敗的位置。