1、多線程爬蟲,可考慮放到線程池,把我們需要解析的URL 地址存入我們的隊(duì)列中,然后去觸發(fā)多線程進(jìn)行操作、
代碼如下
class BaiDuT:
#獲取URL
? ? def __init__(self):
self.Lock=threading.Lock()
#創(chuàng)建一個(gè)線程池
? ? ? ? self.url_queue=queue.Queue()
for iin range(1,21):
url_spider="https://tieba.baidu.com/f?kw=文字控&ie=utf-8&pn="+str(i*50)
self.url_queue.put(url_spider)
print(self.url_queue.queue)
def spider(self):
while self.url_queue.qsize()>0:
#我們對可能出現(xiàn)沖突的地方上鎖
? ? ? ? ? ? if self.Lock.acquire():
url=self.url_queue.get()
print('剩余數(shù)量:%s;處理的線程編號:%s'%(self.url_queue.qsize(),threading.current_thread().name))
#寫具體的爬蟲代碼
? ? ? ? ? ? ? ? self.Lock.release()
if __name__ =='__main__':
c=BaiDuT()
my_thread=[]
for iin range(0,3):
thread2=threading.Thread(target=c.spider)
thread2.start()
my_thread.append(thread2)
for tin my_thread:
t.join()
中間有可能會(huì)出現(xiàn)資源沖突的問題,所以這個(gè)時(shí)候我們應(yīng)該加鎖,防止此類問題。
鎖分為兩種:lock ?Rlock ?這里有一篇比較好的文章,大家可以參考一下。