用于将ip-address转换为其国家/地区代码的Python脚本。 该信息来自网站“https://freegeoip.net/json/”。
除此之外还有更好的方法吗?
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 :(得分:2)
有。
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')