Created
January 25, 2016 03:40
-
-
Save fatelei/84e5f16422389c0d4497 to your computer and use it in GitHub Desktop.
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
| # -*- coding: utf8 -*- | |
| """ | |
| ip_location | |
| ~~~~~~~~~~~ | |
| Using ip138.com to lookup location via ip. | |
| """ | |
| import requests | |
| from bs4 import BeautifulSoup | |
| API = "http://ip138.com/ips1388.asp?ip={}&action=2" | |
| IP138_CHARSET = "gb2312" | |
| DIVIDER = u":" | |
| def lookup_location_via_ip(ip): | |
| """Lookup location via ip. | |
| :param str ip: IP address | |
| :return: Location. | |
| """ | |
| url = API.format(ip) | |
| r = requests.get(url) | |
| r.encoding = IP138_CHARSET | |
| soup = BeautifulSoup(r.text, "html.parser") | |
| tmp = soup.find("li").string.strip() | |
| try: | |
| return tmp.split(DIVIDER)[-1] | |
| except: | |
| return "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment