標籤:程式 .com 網站 tar 調用 連結 過程 功能 網路
我的第00篇部落格Python爬蟲初次開發:
這周四講了Regex,晚上就開始摸索著寫一個網路爬蟲。這個爬蟲的功能就是從指定的網頁開始,爬取這個網頁裡所有的連結,然後進入這些連結繼續爬取新的連結,不斷繼續這個過程,並儲存下所有爬取到的連結。這個爬蟲目前還沒有什麼實際用處,後續可以在此基礎上開發搜尋指定資訊等功能。
這個Python程式將用到以下模組:urllib, re, time
urllib:用來調用urlopen函數開啟連結
re:編譯Regex
time:用於計時[可選]
以下是My Code:
1 from urllib.request import urlopen 2 import re 3 import time 4 fo=open("pc00_result.txt","w") #開啟要用於儲存連結的文字文件 5 list=[] #儲存所有的連結 6 x=0 #爬過的連結次數 7 connected=0 #成功連上的數量 8 num=0 #上一次儲存的最後一個連結的縮印 9 list.append(input("輸入網址:"))10 xn=int(input("輸入爬蟲總次數:"))11 start=time.clock() #開始計時12 while x<=xn:13 if x>=len(list): #次數超出總連結數量就結束14 end=time.clock() #結束計時15 print("爬蟲結束...!")16 print("本次爬蟲共爬過{}個網站,爬得{}個連結".format(connected, len(list)-1))17 print("共耗時{:.3f}s".format(end-start))18 fo.writelines("爬蟲結束...!\n")19 fo.writelines("本次爬蟲共爬過{}個網站,爬得{}個連結\n".format(connected, len(list)-1))20 fo.writelines("共耗時{:.3f}s\n".format(end-start))21 break22 try:23 print("No.{}".format(x))24 fo.writelines("No.{}\n".format(x))25 print("正在串連{}".format(list[x]))26 fo.writelines("正在串連{}\n".format(list[x]))27 temp=urlopen(list[x],timeout=10) #開啟連結 10秒逾時28 temp=temp.read().decode("utf-8") #讀取網頁內容並以utf-8方式解碼29 print("已串連上{}".format(list[x]))30 fo.writelines("已串連上{}\n".format(list[x]))31 patten=re.compile(r‘https?://[^\\\‘"\.].+?[^\\\‘"](?:/|com|org|net|cn|cc|tv)‘)32 print("正在解析{}".format(list[x]))33 fo.writelines("正在解析{}\n".format(list[x]))34 temp0=re.findall(patten, temp) #在之前讀取的內容裡進行匹配35 connected+=1 #成功串連數加一36 for i in range(len(temp0)):37 if temp0[i] not in list: #新連結儲存起來38 list.append(temp0[i])39 for j in range(num,len(list)):40 print(list[j]) #輸出這次新獲得的連結41 fo.writelines(list[j])42 fo.writelines("\n")43 num=len(list)44 print("\n")45 fo.writelines("\n\n")46 except:47 print("{}串連或解析失敗\n\n".format(list[x]))48 fo.writelines("{}串連或解析失敗\n\n\n".format(list[x]))49 x+=150 else:51 x+=152 else:53 end=time.clock()54 print("爬蟲結束...!")55 print("本次爬蟲共爬過{}個網站,爬得{}個連結".format(connected,len(list)-1))56 print("共耗時{:.3f}s".format(end-start))57 fo.writelines("\n")58 fo.writelines("爬蟲結束...!")59 fo.writelines("\n")60 fo.writelines("本次爬蟲共爬過{}個網站,爬得{}個連結".format(connected,len(list)-1))61 fo.writelines("\n")62 fo.writelines("共耗時{:.3f}s".format(end-start))
這個爬蟲的關鍵在於那個Regex:
1 patten=re.compile(r‘https?://[^\\\‘"\.].+?[^\\\‘"](?:/|com|org|net|cn|cc|tv)‘
這句的意思是把那個Regex編譯成Regex對象然後儲存在patten變數裡。
而核心的Regex:https?://[^\\\‘"\.].+?[^\\\‘"](?:/|com|org|net|cn|cc|tv)
是指匹配以http開頭,可能有s(https),加上://,以/、com、org、net、cn、cc、tv結尾的連結
中間的[^\\\‘"\.]指http(s)://後面不能直接跟\ ‘ " .這四個符號
.+?指非貪婪的匹配任何字元
[^\\\‘"]指在com等結尾之前不能出現\ ‘ "的符號
這個運算式花了我很大力氣寫出來,而且匹配仍會有一定的出錯率,目前還不知道有什麼解決辦法。
以上。
【00】Python爬蟲初次開發