2017-03-15 61 views
0

Python腳本將IP地址轉換爲國家代碼。 該信息從網站'https://freegeoip.net/json/'中獲取。python中的國家代碼查找腳本

除此之外還有更好的方法嗎?

import json 
import requests 
import subprocess 

# clearing the screen. 
subprocess.call('clear',shell=True) 
msg = 'country code finder' 

# Making the header. 
print('') 
print(' ',msg.upper()) 
print(' ','-' * len(msg)) 
print('') 

lookup_ip = input(' Enter Your Ip Address : ') 

# Fetching the country code from 'https://freegeoip.net/json/' 
# The reply will be in json format. 
try: 

    lookup_string = 'https://freegeoip.net/json/'+lookup_ip 
    reply = requests.get(lookup_string) 
    geodata= json.loads(reply.text) 
    print('') 
    print(' Country Is ::' , geodata['country_code']) 
    print('') 

except: 
    print(' Unable to Fetch', lookup_string) 
    print('') 
+0

有問題嗎? – Cfreak

+0

我投票結束這個問題作爲題外話,因爲它屬於http://codereview.stackexchange.com/ – kdopen

回答

1

有。

import requests 


ip = input('Enter Your Ip Address: ') 
try: 
    response = requests.get('https://freegeoip.net/json/{0}'.format(ip)) 
    response.raise_for_status() 
    json = response.json() 
    print('Country is {0}'.format(json.get('country_code', 'unknown'))) 
except: 
    print('Unable to fetch')