调用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

转载于:https://www.cnblogs.com/outsrkem/p/11219743.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值