调用API接口,查询手机号码归属地(1)
使用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)
return res
#print('Error code: %s'%res["resultcode"])
#对api接口返回数据处理。
def resTest(resdata):
if resdata["resultcode"] == "200":
#返回有效结果
return resdata["result"]
else:
#定义错误字典,resdata["resultcode"]为接口返回的Error code
Errorinfo = {'province':'Error code', 'city':resdata["resultcode"]}
return Errorinfo
#处理字典为单元组列表
def dictDate(data):
province = data["province"]
city = data["city"]
res.append((phoneNum, province, city))
#print('list res is : %s'%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"
for line in open("test.txt", "r"):
#读取电话号码
phoneNum = line.strip(" \t\r\n")
params = {
"phone": phoneNum,
"key": "0ea8e44e4612fb794c29f4979d238efq",
"dtype" : "json",
}
res = []
#调用getPageCode接口,resTest处理数据
#resd = (getPageCode(url, params))
resdate = resTest((getPageCode(url, params)))
#通过函数dictDate处理为单元组列表,
#[('13676512732', u'\u6d52\u6c5f', u'\u6e19\u5dde')]
resUlt = dictDate(resdate)
writeResult(resUlt)
定义号码文本test.txt
15306525811
13567156311
13968170611
15306525811
13567156311
13968170611
调用API接口,查询手机号码归属地(1)https://www.cnblogs.com/outsrkem/p/11219743.html
调用API接口,查询手机号码归属地(2)https://www.cnblogs.com/outsrkem/p/11221003.html
调用API接口,查询手机号码归属地(3)https://www.cnblogs.com/outsrkem/p/11221604.html
调用phone库,查询手机号码归属地(4)https://www.cnblogs.com/outsrkem/p/11236509.html
作者:Outsrkem
原文链接:https://www.cnblogs.com/outsrkem/p/11219743.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号