使用python批量快速獲取手機號歸屬地及運營商信息;
簡介
本方法是使用python的phone庫查詢,並寫入TXT文檔中,腳本做了高兼容,不會出錯,兼容漢字、空行、異常號等,不會報錯。
項目結構
源文件
查詢結果
使用說明
首次使用腳本,需要配置以下環境:
1、安裝python;
1)、訪問python官網,下載安裝包:https://www.python.org/downloads/,下載版本:3.4及以上版本都行;
2)、安裝python;
2、安裝依賴的庫:命令行執行 pip install phone
使用方法:
1、phoneNum.txt中列出所有需要查詢的號碼,注意盡量不要有中文或者空行之類的;
2、清空result.txt中的內容;
3、雙擊運行getPhoneInfo.py文件,等待執行完畢;
4、result.txt中的內容就是最新的手機號歸屬地信息;
如果手機號后出現Error,請手動查詢,部分號段phone庫不支持;
代碼
#coding=utf-8
from phone import Phone
def getPhoneNum(file): #讀取源文件,獲取待查詢的手機號
try:
with open(file,"r") as f:
phonList = f.readlines() #讀取源手機號文檔中的手機號
#print(phonList)
return phonList #返回手機號列表。phonList
except: #兼容讀取文檔失敗
pass
def getPhoneInfo(phoneNum): #查詢函數
info = Phone().find(phoneNum) #通過phone庫查詢
try: #返回所有查詢的信息
phone = info['phone'] #手機號
province = info['province'] #歸屬地:省份
city = info['city'] #歸屬地,城市
zip_code = info['zip_code'] #郵政編碼
area_code = info['area_code'] #區域編碼
phone_type = info['phone_type'] #手機號運營商
print(phone+"\t"+province+city+"\t"+phone_type)
return ("\n"+phone+" \t"+province+city+" \t"+phone_type) #因為我只需要手機號、區域、運營商,所以只返回這三個字段,其他字段,可以自己按需添加;
except: #兼容查詢失敗的情況
print("\n"+str(phoneNum.strip("\n"))+" \t"+"Error!")
return ("\n"+str(phoneNum.strip("\n"))+" \t"+"Error!")
if __name__ == "__main__":
listPhoneNum = getPhoneNum("phoneNum.txt") #通過getPhoneNum函數,讀取源文件。
listResult = []
for i in listPhoneNum:
try:
res = getPhoneInfo(i.strip("\n"))
listResult.append(res)
with open("result.txt","a") as f: #寫入結果文檔
f.write(res)
f.close()
except: #兼容出錯
res = "\n"+str(i).strip("\n") + "\t" + "Error!"
with open("result.txt","a") as f:
f.write(res)
f.close()