Created
December 9, 2018 13:26
-
-
Save bhuiyanmobasshir94/c8f43acb1db862cc693be7719672384e to your computer and use it in GitHub Desktop.
Solutions to the problem of getting geo information against IP address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
class Scraper: | |
''' Request information and Scrape data class ''' | |
def __init__(self,ip=None): | |
self.address = 'http://ip-api.com/json/' | |
self.ip = ip | |
def get_geo_ip_info(self): | |
'''Collect geo ip info''' | |
if self.ip != None and self.ip: | |
url = self.address + '{}'.format(self.ip) | |
try: | |
json_geo_ip_res = requests.get(url) | |
json_geo_ip_data = json_geo_ip_res.json() | |
except Exception as e: | |
print("Error: {}".format(e)) | |
else: | |
if(json_geo_ip_data['status'] and json_geo_ip_data['status'] == 'success'): | |
self.display_geo_ip_info(json_geo_ip_data) | |
else: | |
print("Sorry status was failure and message was `{}`".format(json_geo_ip_data['message'])) | |
else: | |
url = self.address | |
try: | |
json_geo_ip_res = requests.get(url) | |
json_geo_ip_data = json_geo_ip_res.json() | |
except Exception as e: | |
print("Error: {}".format(e)) | |
else: | |
if(json_geo_ip_data['status'] and json_geo_ip_data['status'] == 'success'): | |
self.display_geo_ip_info(json_geo_ip_data) | |
else: | |
print("Sorry status was failure and message was `{}`".format(json_geo_ip_data['message'])) | |
def display_geo_ip_info(self,data): | |
'''Display geo ip info''' | |
print("{}, {} ({})".format(data['city'],data['regionName'],data['country'])) | |
if __name__ == '__main__': | |
ip_address = input('Enter your ip address:') | |
if ip_address != None and ip_address: | |
obj = Scraper(ip_address) | |
obj.get_geo_ip_info() | |
else: | |
obj = Scraper() | |
obj.get_geo_ip_info() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment