标签:json 结果 def page __name__ api append asd 文件
使用https://www.juhe.cn/
提供的接口,查询归属地
在官网注册key即可使用。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json, urllib, sys
from urllib import urlencode, urlopen
reload(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
15306525811
13567156311
13968170611
15306525811
13567156311
13968170611
标签:json 结果 def page __name__ api append asd 文件
原文地址:https://www.cnblogs.com/outsrkem/p/11219743.html