Skip to content

Instantly share code, notes, and snippets.

@fatelei
Created January 25, 2016 03:40
Show Gist options
  • Select an option

  • Save fatelei/84e5f16422389c0d4497 to your computer and use it in GitHub Desktop.

Select an option

Save fatelei/84e5f16422389c0d4497 to your computer and use it in GitHub Desktop.
# -*- 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