做爬蟲項目時,我們需要考慮一個爬蟲在爬取時會遇到各種情況(網站驗證,ip封禁),導緻爬蟲程式中斷,這時我們已經爬取過一些資料,再次爬取時這些資料就可以忽略,是以我們需要在爬蟲項目中設定一個中斷重連的功能,使其在重新運作時從之前斷掉的位置重新爬取資料。
實作該功能有很多種做法,我自己就有好幾種思路,但是真要自己寫出來就要費很大的功夫,下面我就把自己好不容易拼湊出來的代碼展示出來吧。
首先是來介紹代碼的思路:
将要爬取的網站連接配接存在一個數組new_urls中,爬取一個網址就将它移入另一個數組old_urls中,爬取網站時,就看它是在哪一個數組中,然後再決定要不要爬取。
下面展示代碼(從别處抄的):
class UrlManager(object):
def __init__(self): #定義兩個數組
self.new_urls=set()
self.old_urls=set()
def add_new_url(self, url): #将一個url加入到new_urls數組中
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
self.new_urls.add(url)
def add_new_urls(self, urls): #将多個url加入到new_urls數組中
if urls is None or len(urls)==0:
return
for url in urls :
self.add_new_url(url)
def has_new_url(self): #判斷url是否為空
return len(self.new_urls)!=0
def get_new_url(self):
#list.pop()預設移除清單中最後一個元素對象
new_url=self.new_urls.pop()
self.old_urls.add(new_url)
return new_url
這個類實作了中斷重連的基本功能,但是當我們要爬取的網址非常的,那這就對我們電腦的記憶體要求非常大,是以我們要将數組儲存到文檔中,增加一個從文檔中提取網址的過程。
下面看代碼:
class UrlManager(object):
def __init__(self): #建立兩個數組的檔案
with open('new_urls.txt','r+') as new_urls:
self.new_urls = new_urls.read()
with open('old_urls.txt','r+') as old_urls:
self.old_urls = old_urls.read()
def add_new_url(self, url): #添加url到new_ulrs檔案中
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
with open('new_urls.txt', 'a') as new_urls:
new_urls.write(url)
else:
print('url had done')
def add_new_urls(self, urls): #添加多個url到new_ulrs檔案中
# if urls is None or (len(url) == 0 for url in urls):
if urls is None:
print('url is none')
return
for url in urls:
if urls is None:
print('url is none')
return
else:
self.add_new_url(url)
def has_new_url(self):
return len(self.new_urls) != 0
def get_new_url(self):
new_url = get_last_line('new_urls.txt') #讀取new_urls檔案中最後一個url
del_last_url('new_urls.txt',new_url) #删除new_urls檔案中最後一個url
add_old_urls('old_urls.txt',new_url) #将讀取出來的url添加入old_urls數組中
return new_url
其中的get_last_line()函數有些複雜,這也是我卡時間最長的一塊,
import os
def get_last_line(inputfile):
filesize = os.path.getsize(inputfile)
blocksize = 1024
dat_file = open(inputfile, 'rb')
last_line = b""
lines = []
if filesize > blocksize:
maxseekpoint = (filesize // blocksize) # 這裡的除法取的是floor
maxseekpoint -= 1
dat_file.seek(maxseekpoint * blocksize)
lines = dat_file.readlines()
while ((len(lines) < 2) | ((len(lines) >= 2) & (lines[1] == b'\r\n'))): # 因為在Windows下,是以是b'\r\n'
# 如果清單長度小于2,或者雖然長度大于等于2,但第二個元素卻還是空行
# 如果跳出循環,那麼lines長度大于等于2,且第二個元素肯定是完整的行
maxseekpoint -= 1
dat_file.seek(maxseekpoint * blocksize)
lines = dat_file.readlines()
elif filesize: # 檔案大小不為空
dat_file.seek(0, 0)
lines = dat_file.readlines()
if lines: # 清單不為空
for i in range(len(lines) - 1, -1, -1):
last_line = lines[i].strip()
if (last_line != b''):
break # 已經找到最後一個不是空行的
dat_file.close()
return last_line
def del_last_url(fname,part):
with open(fname,'rb+') as f:
a = f.read()
a = a.replace(part,b'')
with open(fname,'wb+') as f:
f.write(a)
def add_old_urls(fname,new_url):
line = new_url + b'\r'
with open(fname,'ab') as f:
f.write(line)
好了,爬蟲的中斷重連的功能就實作了,下面要做的就是将該功能接入爬蟲項目中,比較簡單。