使用https://www.juhe.cn/
提供的接口,查询归属地
在官网注册key即可使用。
#!/usr/bin/python# -*- coding: utf-8 -*-import json, urllib, sys from urllib import urlencode, urlopenreload(sys)sys.setdefaultencoding('utf8')#调用接口,获取结果为二维字典def getPageCode(url, params): params = urlencode(params) f = urllib.urlopen(url, params) content = f.read() res = json.loads(content) if res["resultcode"] == "200": return res else: print('Error code: %s'%res["resultcode"])#处理字典为单元组列表 def dictDate(data): province = data["province"] city = data["city"] res.append((phoneNum, province, city)) #print res return res#追加保存文件def writeResult(resultdata): f = open("location.log", "a") for num,item,cit in resultdata: f.write("%s\t" %num) f.write("%s," %item) f.write("%s" %cit) f.write("\n") f.close()if __name__ == "__main__": url = "http://apis.juhe.cn/mobile/get" apiKey = "79aac02768158ebeb43c6asd2e2qdwew" for line in open("test.txt", "r"): #读取电话号码 phoneNum = line.strip(" \t\r\n") params = { "phone": phoneNum, "key": apiKey, "dtype" : "json", } res = [] #调用getPageCode(API接口),通过函数dictDate处理为单元组列表;[('13676512732', u'\u6d52\u6c5f', u'\u6e19\u5dde')] resUlt = dictDate((getPageCode(url, params))["result"]) writeResult(resUlt)
test.txt
153065258111356715631113968170611153065258111356715631113968170611