本篇內容介紹了“如何調用API接口,查詢手機號碼歸屬地”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
以聚合數據平臺的接口為例,講解下如何從mysql數據庫獲取電話號碼,查詢歸屬地并插入到數據庫。
代碼示例如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json, urllib, sys, pymysql
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))
#將省和市處理為一個元素:遼寧,葫蘆島
res1,res2,res3 = res[0][0],res[0][1],res[0][2]
symbol = ','
resz = [(res1,res2+symbol+res3)]
#print('list res is : %s'%resz)
return resz
#連接數據庫
dblink = pymysql.connect(
host = "10.10.10.31",
user = "abc",
password = "123456",
database = "test",
charset = "utf8")
#查詢數據
def select(db):
cursor = db.cursor()
cursor.execute("select phoneNum from test.userinfo")
#cursor.execute("select phoneNum from test.userinfo order by id;")
# 使用 fetchone() 方法獲取單條數據.fetchall()獲取所有行
data = cursor.fetchall()
#print data
return data
#插入數據
def install(db, data):
cursor = db.cursor()
sql = "update `test`.`userinfo` set location=%s where phoneNum = %s"
#data=(第一個%s,第二個%s)
data = (data[0][1], data[0][0])
cursor.execute(sql, data)
db.commit()
if __name__ == "__main__":
url = "http://apis.juhe.cn/mobile/get"
for phoneNum in select(dblink):
phoneNum = phoneNum[0]
params = {
"phone": phoneNum,
"key": "0ea8e44e4612fb794c29asdfde48hg",
"dtype" : "json",
}
res = []
#調用getPageCode接口,resTest處理數據
resdate = resTest((getPageCode(url, params)))
#通過函數dictDate處理為單元組列表,[('12676512732', u'\u6d52\u6c5f,\u6e19\u5dde')]
resUlt = dictDate(resdate)
install(dblink, resUlt)
dblink.close()“如何調用API接口,查詢手機號碼歸屬地”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。