pythongeoip使用json查找国家

2024-04-25 14:06:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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)   

它没有答复任何国家我能得到帮助来解决这个问题吗?在


Tags: namefromimportjsonurlcitytimeos
2条回答

首先,服务器看起来是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))

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

^{pr2}$

服务器可能早就启动了,问题实际上可能有不同的原因,例如json.loads()可能失败。如果您如上面所示更改异常处理程序,您将能够看到它失败的地方。在

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

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

可能是api过载,或者不再存在。在

相关问题 更多 >