首页 >后端开发 >Python教程 >Python实现号码归属地查询功能

Python实现号码归属地查询功能

巴扎黑
巴扎黑原创
2017-08-09 10:57:383045浏览

这篇文章主要介绍了Python实现的手机号归属地相关信息查询功能,涉及Python文件读取及基于第三方接口调用查询信息的相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python实现的手机号归属地相关信息查询功能。分享给大家供大家参考,具体如下:

根据指定的手机号码,查询其归属地等相关信息,Python实现:

手机号文件:test.txt


13693252552
13296629989
13640810839
15755106631
15119622732
13904446048
18874791953
13695658500
13695658547
15950179080
15573462779
15217624651
15018485989
13706522482
13666519777
13666515188
18857287528
15575394501

python实现:


# coding=UTF-8
# get provider information by phoneNumber
from urllib import urlopen
import re
# get html source code for url
def getPageCode(url):
  file = urlopen(url)
  text = file.read()
  file.close()
#  text = text.decode("utf-8")   # depending on coding of source code responded
  return text
# parse html source code to get provider information
def parseString(src, result):
  pat = []
  pat.append(&#39;(?<=归属地:</span>).+(?=<br />)&#39;)
  pat.append(&#39;(?<=卡类型:</span>).+(?=<br />)&#39;)
  pat.append(&#39;(?<=运营商:</span>).+(?=<br />)&#39;)
  pat.append(&#39;(?<=区号:</span>)\d+(?=<br />)&#39;)
  pat.append(&#39;(?<=邮编:</span>)\d+(?=<br />)&#39;)
  item = []
  for i in range(len(pat)):
    m = re.search(pat[i], src)
    if m:
      v = m.group(0)
      item.append(v)
  return item
# get provider by phoneNum
def getProvider(phoneNum, result):
  url = "http://www.sjgsd.com/n/?q=%s" %phoneNum
  text = getPageCode(url)
  item = parseString(text, result)
  result.append((phoneNum, item))
# write result to file
def writeResult(result):
  f = open("result.log", "w")
  for num, item in result:
    f.write("%s:\t" %num)
    for i in item:
      f.write("%s,\t" %i)
    f.write("\n")
  f.close()
if __name__ == "__main__":
  result = []
  for line in open("test.txt", "r"):
    phoneNum = line.strip(" \t\r\n")
    getProvider(phoneNum, result)
    print("%s is finished" %phoneNum)
  writeResult(result)

以上是Python实现号码归属地查询功能的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn