03-0006 Python批量查詢手機歸屬地

1.源碼

1.1 文件切割以及數據查詢部分

import threading
import urllib
import urllib.request

# 線程結束的標誌
exitFlag = 0
#線程個數
thread_num=0

# 文件分割
# 每一百個手機號,放進一個文件裏面,依次命名
# 將其放進file_cut文件夾中
# 這裏使用的是相對路徑,需要自己新建對應的文件夾
f = open("data.txt")             # 返回一個文件對象
fo=open("file_cut/file1.txt","w")
line = f.readline()             # 調用文件的 readline()方法
count=1
while line:
    print(line)                 # 後面跟 ',' 將忽略換行符
    fo.write(line)
    line = f.readline()
    if count%100==0:
        fo.close()
        path='file_cut/file'+str(int(count/100)+1)+'.txt'
        fo = open(path, "w")
    count+=1
fo.close()
f.close()

# 獲取線程數
# 線程的個數等於文件的個數
thread_num=int(count/100)+1


# 多線程處理
class myThread(threading.Thread):  # 繼承父類threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):  # 把要執行的代碼寫到run函數裏面 線程在創建後會直接運行run函數
        print("Starting " + self.name)
        phone_ser(self.threadID)
        print("Exiting " + self.name)
# 用於查詢歸屬地,將返回內容寫入對應的文件之中,根據線程的編號
def phone_ser(threadID):
    file_path='file_cut/file'+str(threadID+1)+'.txt'
    file_path2='file_com/file'+str(threadID+1)+'.txt'
    file = open(file_path)
    file2 = open(file_path2, "w")
    line = file.readline()
    while line:
        url = 'http://mobsec-dianhua.baidu.com/dianhua_api/open/location?tel=' + line
        req = urllib.request.Request(url)
        res = urllib.request.urlopen(req)
        html = res.read().decode('utf-8')
        # print(html)
        file2.write(html)
        file2.write("\n")
        line = file.readline()
    file.close()
    file2.close()

thread=[]
# 循環創建線程
for i in range(0,thread_num):
    thread_name="Thread"+str(i)
    temp_thread=myThread(i,thread_name,1)
    thread.append(temp_thread)

# 循環開啓線程
for i in range(0,thread_num):
    thread[i].start()

1.2 合併部分

# 數據整理
import re
file_path2 = 'file_com.txt'
file2 = open(file_path2, "w")
for i in range(0,113):
    file_path = 'file_com/file' + str(i + 1) + '.txt'
    file = open(file_path)
    line=file.readline()
    while line:
        pattern = re.compile(r'\"(.*?)\"')
        str_list = pattern.findall(line)
        new_line=str_list[1]+" "+str_list[5]+" "+str_list[7]+" "+str_list[11]+"\n"
        file2.write(new_line)
        line=file.readline()
    file.close()

file2.close()
# 這一部分的備註比較少,因爲在python裏面,文件操作確實很簡單。

2.結果

file_com存儲需要合併的文件【必須要有】
file_cut存儲切割之後的文件【必須要有】
data.txt是原始數據,可以直接從excel中進行復制粘貼【必須要有】
file_com.txt是最終要得到的文件【自動生成,可以覆蓋】
file_com.py數據合併部分的代碼
phonenum.py數據切割及查詢部分的代碼

在這裏插入圖片描述

file_com文件夾

在這裏插入圖片描述

file_cut文件夾

在這裏插入圖片描述

文件名都一樣但是大小不一樣,當運行過代碼之後一定要生成對應數量的文件。
運行的時候在編譯器裏面會有[finished]的標誌,但是直接用python.exe文件運行是不會有這些的,會自己退出,如果中途卡住,等了好久也不退出,說明該程序可能已經被檢測爲了爬蟲,需要重新啓動。
程序尚且有不足之處,沒有對於線程卡住的情況進行處理,可以對於每個線程添加時間限制,到時間之後自動結束,然後自動重啓,直到該線程結束。
但是上面的機制,還不會寫,所以就沒有寫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章