__author__ = 'jk409'
#python3.4
#使用聚合api接口
#根据手机号查询isp运营商,并更新到表里
import sys,time,urllib.request,urllib.parse
sys.path.append('./')
import sql
import json
#------------------------------------------------------
def Mysqls():
return sql.Mysql('127.0.0.1','root','123456','msc')
#------------------------------------------------------
def request1(phone,appkey, m="GET"):
url = "http://apis.juhe.cn/mobile/get"
params = {
"phone" : phone, #需要查询的手机号码或手机号码前7位
"key" : appkey, #应用APPKEY(应用详细页查询)
"dtype" : "json", #返回数据的格式,xml或json,默认json
}
params = urllib.parse.urlencode(params)
if m =="GET":
f = urllib.request.urlopen("%s?%s" % (url,params))
else:
f = urllib.request.urlopen(url, params)
content = f.read().decode('utf-8')
res = json.loads(content)
if res:
error_code = res["error_code"]
if error_code == 0:
#成功请求
#print (res["result"])
return res["result"]["company"]
else:
print("%s:%s" % (res["error_code"],res["reason"]))
else:
print( "request api error")
def run():
mysql=Mysqls()
sqls="select uid,phone from msc_user_def where isp is null order by uid limit 10 "
try:
res=mysql.cmd(sqls)
except:
pass
mysql.close()
res_list=[list(x) for x in res]
#for i in res_list:
# print(i[0])
return res_list
if __name__ == "__main__":
dc={}
appkey='a28516a0d19a*************' #需要正确填写你的appkey
phone_list=run()
print('请稍后,正常查询......')
for i in phone_list:
isp=request1(i[1],appkey,'GET')
#print(i[0],i[1],isp)
dc[i[0]]={}
dc[i[0]]['phone']=str(i[1])
dc[i[0]]['isp']=isp
#print(dc)
#isp_type:1移动,2电信,3联通
for i in dc:
isp_type=0
mysql=Mysqls()
if dc[i]['isp']=="中国移动":isp_type=1
if dc[i]['isp']=='中国电信':isp_type=2
if dc[i]['isp']=='中国联通':isp_type=3
print(dc[i]['phone'],dc[i]['isp'])
print(isp_type)
sqls="update msc_user_def set isp='%s',isp_type='%s' where phone='%s'"
try:
mysql.cmd(sqls%(dc[i]['isp'],isp_type,dc[i]['phone']))
#mysql.commit()
except:
print('phone',dc[i]['phone'])
pass
mysql.close()
pass
转载于:https://my.oschina.net/jk409/blog/659115