Last active
August 29, 2015 14:02
-
-
Save cgwxyz/9794eb25f69f023d2cb0 to your computer and use it in GitHub Desktop.
根据IP通过sogou接口获取地理位置相关信息
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
def ip2addr(ip): | |
import urllib | |
import httplib | |
import chardet #字符集检测Module,返回dict | |
config = { | |
'api_host':'www.sogou.com', | |
'api_script':'/websearch/features/ipsearch.jsp' | |
} | |
params = {'ip':ip} | |
params = urllib.urlencode(params) | |
headers = {"Accept": "text/html"} | |
conn = httplib.HTTPConnection(config['api_host'], 80, timeout=10) | |
conn.request("GET",config['api_script']+'?'+params) | |
response = conn.getresponse() | |
if response.status == 200 : | |
data = response.read() | |
tmp_arr = data.split('>') | |
if 2 == len(tmp_arr) : | |
tmp_addr = tmp_arr[1].strip().lstrip().rstrip() | |
addr = tmp_addr[0:len(tmp_addr)-3] | |
curr_coding = chardet.detect(addr) #检测字符集,转为UTF8输出 | |
print curr_coding | |
return addr.decode(curr_coding['encoding']).encode('UTF-8') | |
return '' | |
conn.close() | |
return '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment