Created
February 5, 2012 15:45
-
-
Save laginha/1746153 to your computer and use it in GitHub Desktop.
Get geolocation information from whatismyipaddress.com
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
from requests import get | |
import re, json, optparse | |
class WhatIsMyIP: | |
@staticmethod | |
def request( ip ): | |
clean_html = lambda x: ''.join( [ i.strip() for i in x.split('\n')] ) | |
url = lambda x: "http://whatismyipaddress.com/ip/%s" %x | |
response = get( url(ip), headers={'User-Agent': 'Mozilla/5.0'} ) | |
return clean_html( response.content ) | |
@staticmethod | |
def to_json( html ): | |
table = lambda x: re.findall( r'</h2><table><tr>(.+)</tr></table>', x )[0] | |
key = lambda x: re.findall( r'<th>(.+):</th>', x )[0] | |
value = lambda x: re.findall( r'<td>([a-zA-Z0-9\.\-]+)', x )[0] | |
return dict( [ (key(i), value(i)) for i in table(html).split('</tr><tr>') ] ) | |
if __name__ == '__main__': | |
parser = optparse.OptionParser() | |
parser.add_option('--ip', action='store', help='IP address of which you wish to get geolocation information') | |
opts, sources = parser.parse_args() | |
if opts.ip: | |
html = WhatIsMyIP.request( opts.ip ) | |
dict_ = WhatIsMyIP.to_json( html ) | |
print json.dumps( dict_, indent=2 ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hey, your coding is very fine I create a new tool https://codebeautify.org/hostname-to-ip this tool is very simple and easy they will be very useful too.