python手机号前7位归属地爬虫代码实例

需求分析

项目上需要用到手机号前7位,判断号码是否合法,还有归属地查询。旧的数据是几年前了太久了,打算用python爬虫重新爬一份

单线程版本

# coding:utf-8
import requests
from datetime import datetime

class PhoneInfoSpider:
  def __init__(self, phoneSections):
    self.phoneSections = phoneSections

  def phoneInfoHandler(self, textData):
    text = textData.splitlines(True)
    # print("text length:" + str(len(text)))

    if len(text) >= 9:
      number = text[1].split('\'')[1]
      province = text[2].split('\'')[1]
      mobile_area = text[3].split('\'')[1]
      postcode = text[5].split('\'')[1]
      line = "number:" + number + ",province:" + province + ",mobile_area:" + mobile_area + ",postcode:" + postcode
      line_text = number + "," + province + "," + mobile_area + "," + postcode
      print(line_text)
      # print("province:" + province)

      try:
        f = open('./result.txt', 'a')
        f.write(str(line_text) + '\n')
      except Exception as e:
        print(Exception, ":", e)

  def requestPhoneInfo(self, phoneNum):
    try:
      url = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=' + phoneNum
      response = requests.get(url)
      self.phoneInfoHandler(response.text)
    except Exception as e:
      print(Exception, ":", e)

  def requestAllSections(self):
    # last用于接上次异常退出前的号码
    last = 0
    # last = 4
    # 自动生成手机号码,后四位补0
    for head in self.phoneSections:
      head_begin = datetime.now()
      print(head + " begin time:" + str(head_begin))

      # for i in range(last, 10000):
      for i in range(last, 10):
        middle = str(i).zfill(4)
        phoneNum = head + middle + "0000"
        self.requestPhoneInfo(phoneNum)
      last = 0

      head_end = datetime.now()
      print(head + " end time:" + str(head_end))

if __name__ == '__main__':
  task_begin = datetime.now()
  print("phone check begin time:" + str(task_begin))

  # 电信,联通,移动,虚拟运营商
  dx = ['133', '149', '153', '173', '177', '180', '181', '189', '199']
  lt = ['130', '131', '132', '145', '146', '155', '156', '166', '171', '175', '176', '185', '186', '166']
  yd = ['134', '135', '136', '137', '138', '139', '147', '148', '150', '151', '152', '157', '158', '159', '172',
     '178', '182', '183', '184', '187', '188', '198']
  add = ['170']
  all_num = dx + lt + yd + add

  # print(all_num)
  print(len(all_num))

  # 要爬的号码段
  spider = PhoneInfoSpider(all_num)
  spider.requestAllSections()

  task_end = datetime.now()
  print("phone check end time:" + str(task_end))

发现爬取一个号段,共10000次查询,单线程版大概要多1个半小时,太慢了。

多线程版本

# coding:utf-8
import requests
from datetime import datetime
import queue
import threading

threadNum = 32

class MyThread(threading.Thread):
  def __init__(self, func):
    threading.Thread.__init__(self)
    self.func = func

  def run(self):
    self.func()

def requestPhoneInfo():
  global lock
  while True:
    lock.acquire()
    if q.qsize() != 0:
      print("queue size:" + str(q.qsize()))
      p = q.get() # 获得任务
      lock.release()

      middle = str(9999 - q.qsize()).zfill(4)
      phoneNum = phone_head + middle + "0000"
      print("phoneNum:" + phoneNum)

      try:
        url = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=' + phoneNum
        # print(url)
        response = requests.get(url)
        # print(response.text)
        phoneInfoHandler(response.text)
      except Exception as e:
        print(Exception, ":", e)
    else:
      lock.release()
      break

def phoneInfoHandler(textData):
  text = textData.splitlines(True)

  if len(text) >= 9:
    number = text[1].split('\'')[1]
    province = text[2].split('\'')[1]
    mobile_area = text[3].split('\'')[1]
    postcode = text[5].split('\'')[1]
    line = "number:" + number + ",province:" + province + ",mobile_area:" + mobile_area + ",postcode:" + postcode
    line_text = number + "," + province + "," + mobile_area + "," + postcode
    print(line_text)
    # print("province:" + province)

    try:
      f = open('./result.txt', 'a')
      f.write(str(line_text) + '\n')
    except Exception as e:
      print(Exception, ":", e)

if __name__ == '__main__':
  task_begin = datetime.now()
  print("phone check begin time:" + str(task_begin))

  dx = ['133', '149', '153', '173', '177', '180', '181', '189', '199']
  lt = ['130', '131', '132', '145', '155', '156', '166', '171', '175', '176', '185', '186', '166']
  yd = ['134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '157', '158', '159', '172', '178',
     '182', '183', '184', '187', '188', '198']
  all_num = dx + lt + yd
  print(len(all_num))

  for head in all_num:
    head_begin = datetime.now()
    print(head + " begin time:" + str(head_begin))

    q = queue.Queue()
    threads = []
    lock = threading.Lock()

    for p in range(10000):
      q.put(p + 1)

    print(q.qsize())

    for i in range(threadNum):
      middle = str(i).zfill(4)
      global phone_head
      phone_head = head

      thread = MyThread(requestPhoneInfo)
      thread.start()
      threads.append(thread)
    for thread in threads:
      thread.join()

    head_end = datetime.now()
    print(head + " end time:" + str(head_end))

  task_end = datetime.now()
  print("phone check end time:" + str(task_end))

多线程版的1个号码段1000条数据,大概2,3min就好,cpu使用飙升,大概维持在70%左右。

总共40多个号段,爬完大概1,2个小时,总数据41w左右

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • python实现获取Ip归属地等信息

    如果你有一批IP地址想要获得这些IP具体的信息,比如归属国家,城市等,最好的办法当时是调用现有的api接口来获取,我在之前就写过一篇文章,是关于我的博客被莫名攻击的时,就有获取过一批IP,攻击的时候当时是恢复业务重要,IP该封的就要封,攻击过后这个攻击者的IP信息,自己就可以分析下都来自哪里,有没有什么特征,帮助提示自己网站的安全性,今天这个脚本就是根据提供的IP获得IP归属的具体信息,脚本如下: #!/usr/bin/env python import requests import csv

  • Python实现的手机号归属地相关信息查询功能示例

    本文实例讲述了Python实现的手机号归属地相关信息查询功能.分享给大家供大家参考,具体如下: 根据指定的手机号码,查询其归属地等相关信息,Python实现: 手机号文件:test.txt 13693252552 13296629989 13640810839 15755106631 15119622732 13904446048 18874791953 13695658500 13695658547 15950179080 15573462779 15217624651 15018485989

  • Python抓取手机号归属地信息示例代码

    前言 本文给大家介绍的是利用Python抓取手机归属地信息,文中给出了详细的示例代码,相信对大家的理解和学习很有帮助,以下为Python代码,较为简单,供参考. 示例代码 # -*- coding:utf-8 -*- import requests,re o = open('data.txt','a') e = open('error.txt','a') baseUrl = 'http://www.iluohe.com/' r = requests.get('http://www.iluohe.

  • Python查询IP地址归属完整代码

    本文实例为大家分享了Python查询IP地址归属的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*- #查找IP地址归属地 #writer by keery_log #Create time:2013-10-30 #Last update:2013-10-30 #用法: python chk_ip.py www.google.com |python chk_ip.py 8.8.8.8 |python chk_ip.py

  • Python使用淘宝API查询IP归属地功能分享

    网上有很多方法能够过去到IP地址归属地的脚本,但是我发现淘宝IP地址库的信息更详细些,所以用shell写个脚本来处理日常工作中一些IP地址分析工作. 脚本首先是从http://ip.taobao.com/的数据接口获取IP地址的JSON格式的数据信息,在使用一个python脚本来把Unicode字符转换成UTF-8编码. Shell脚本内容: 复制代码 代码如下: #!/bin/bash ipInfo() {   for i in `cat list`   do     TransCoding=

  • Python手机号码归属地查询代码

    简单的一个例子,是以前用Dephi写的,前不久刚实现了一个在Python中使用Delphi控件来编写界面程序,于是趁热写一个类似的的查询方案. 本实例是通过www.ip138.com这个网站来查询的,这里需要的几个知识点,就是用Python模拟网页提交数据,获得数据返回信息,以及对返回的Html信息进行解析,模拟Http提交,Python自带有一个urllib和urllib2这两个库,相当方便,只是奇怪,为什么不将两个库合并成一个,这样来的更方便.然后就是窗体了,窗体还是用我之前写的一个Pyth

  • python手机号前7位归属地爬虫代码实例

    需求分析 项目上需要用到手机号前7位,判断号码是否合法,还有归属地查询.旧的数据是几年前了太久了,打算用python爬虫重新爬一份 单线程版本 # coding:utf-8 import requests from datetime import datetime class PhoneInfoSpider: def __init__(self, phoneSections): self.phoneSections = phoneSections def phoneInfoHandler(sel

  • Python tornado队列示例-一个并发web爬虫代码分享

    Queue Tornado的tornado.queue模块为基于协程的应用程序实现了一个异步生产者/消费者模式的队列.这与python标准库为多线程环境实现的queue模块类似. 一个协程执行到yieldqueue.get会暂停,直到队列中有条目.如果queue有上限,一个协程执行yieldqueue.put将会暂停,直到队列中有空闲的位置. 在一个queue内部维护了一个未完成任务的引用计数,每调用一次put操作便会增加引用计数,而调用task_done操作将会减少引用计数. 下面是一个简单的

  • python通过伪装头部数据抵抗反爬虫的实例

    0x00 环境 系统环境:win10 编写工具:JetBrains PyCharm Community Edition 2017.1.2 x64 python 版本:python-3.6.2 抓包工具:Fiddler 4 0x01 头部数据伪装思路 通过http向服务器提交数据,以下是通过Fiddler 抓取python没有伪装的报文头信息 GET /u012870721 HTTP/1.1 Accept-Encoding: identity Host: blog.csdn.net User-Ag

  • Python实现简单网页图片抓取完整代码实例

    利用python抓取网络图片的步骤是: 1.根据给定的网址获取网页源代码 2.利用正则表达式把源代码中的图片地址过滤出来 3.根据过滤出来的图片地址下载网络图片 以下是比较简单的一个抓取某一个百度贴吧网页的图片的实现: # -*- coding: utf-8 -*- # feimengjuan import re import urllib import urllib2 #抓取网页图片 #根据给定的网址来获取网页详细信息,得到的html就是网页的源代码 def getHtml(url): pag

  • python使用beautifulsoup4爬取酷狗音乐代码实例

    这篇文章主要介绍了python使用beautifulsoup4爬取酷狗音乐代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 小编经常在网上听一些音乐但是有一些网站好多音乐都是付费下载的正好我会点爬虫技术,空闲时间写了一份,截止4月底没有问题的,会下载到当前目录,只要按照bs4库就好, 安装方法:pip install beautifulsoup4 完整代码如下:双击就能直接运行 from bs4 import BeautifulSoup

  • Python编程实现线性回归和批量梯度下降法代码实例

    通过学习斯坦福公开课的线性规划和梯度下降,参考他人代码自己做了测试,写了个类以后有时间再去扩展,代码注释以后再加,作业好多: import numpy as np import matplotlib.pyplot as plt import random class dataMinning: datasets = [] labelsets = [] addressD = '' #Data folder addressL = '' #Label folder npDatasets = np.zer

  • python图片二值化提高识别率代码实例

    这篇文章主要介绍了python图片二值化提高识别率代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码如下 import cv2from PIL import Imagefrom pytesseract import pytesseractfrom PIL import ImageEnhanceimport reimport string def createFile(filePath,newFilePath): img = Image

  • python基于FTP实现文件传输相关功能代码实例

    这篇文章主要介绍了python基于FTP实现文件传输相关功能代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 本实例有文件传输相关功能,包括:文件校验.进度条打印.断点续传 客户端示例: import socket import json import os import hashlib CODE = { '1001':'重新上传文件' } def file_md5(file_path): obj = open(file_path,'rb

  • Python小程序 控制鼠标循环点击代码实例

    这篇文章主要介绍了Python小程序 控制鼠标循环点击代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 from ctypes import * import pyautogui import time time.sleep(5) while 1: pyautogui.click(400, 400, clicks=1, interval=0.0, button='left') time.sleep(10) Note: 坐标(400,400

  • Python通过递归获取目录下指定文件代码实例

    这篇文章主要介绍了python通过递归获取目录下指定文件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 获取一个目录下所有指定格式的文件是实际生产中常见需求. import os #递归获取一个目录下所有的指定格式的文件 def get_jsonfile(path,file_list): dir_list=os.listdir(path) for x in dir_list: new_x=os.path.join(path,x) if

随机推荐