python爬蟲中多線程的使用詳解
queue介紹
queue是python的標準庫,俗稱隊列.可以直接import引用,在python2.x中,模塊名為Queue。python3直接queue即可
在python中,多個線程之間的數(shù)據(jù)是共享的,多個線程進行數(shù)據(jù)交換的時候,不能夠保證數(shù)據(jù)的安全性和一致性,所以當多個線程需要進行數(shù)據(jù)交換的時候,隊列就出現(xiàn)了,隊列可以完美解決線程間的數(shù)據(jù)交換,保證線程間數(shù)據(jù)的安全性和一致性。
#多線程實戰(zhàn)栗子(糗百)
#用一個隊列Queue對象,
#先產(chǎn)生所有url,put進隊列;
#開啟多線程,把queue隊列作為參數(shù)傳入
#主函數(shù)中讀取url
import requests
from queue import Queue
import re,os,threading,time
# 構(gòu)造所有ip地址并添加進queue隊列
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
urlQueue = Queue()
[urlQueue.put('http://www.qiumeimei.com/image/page/{}'.format(i)) for i in range(1,14)]
def get_image(urlQueue):
while True:
try:
# 不阻塞的讀取隊列數(shù)據(jù)
url = urlQueue.get_nowait()
# i = urlQueue.qsize()
except Exception as e:
break
print('Current Thread Name %s, Url: %s ' % (threading.currentThread().name, url))
try:
res = requests.get(url, headers=headers)
url_infos = re.findall('data-lazy-src="(.*?)"', res.text, re.S)
for url_info in url_infos:
if os.path.exists(img_path + url_info[-20:]):
print('圖片已存在')
else:
image = requests.get(url_info, headers=headers)
with open(img_path + url_info[-20:], 'wb') as fp:
time.sleep(1)
fp.write(image.content)
print('正在下載:' + url_info)
except Exception as e:
print(e)
if __name__ == '__main__':
startTime = time.time()
# 定義圖片存儲路徑
img_path = './img/'
if not os.path.exists(img_path):
os.mkdir(img_path)
threads = []
# 可以調(diào)節(jié)線程數(shù), 進而控制抓取速度
threadNum = 4
for i in range(0, threadNum):
t = threading.Thread(target=get_image, args=(urlQueue,))
threads.append(t)
for t in threads:
t.start()
for t in threads:
# 多線程多join的情況下,依次執(zhí)行各線程的join方法, 這樣可以確保主線程最后退出, 且各個線程間沒有阻塞
t.join()
endTime = time.time()
print('Done, Time cost: %s ' % (endTime - startTime))
總結(jié)
以上所述是小編給大家介紹的python爬蟲中多線程的使用詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
- Python基礎進階之海量表情包多線程爬蟲功能的實現(xiàn)
- python3爬蟲中多線程進行解鎖操作實例
- python3爬蟲GIL修改多線程實例講解
- python3爬蟲中多線程的優(yōu)勢總結(jié)
- python爬蟲開發(fā)之使用Python爬蟲庫requests多線程抓取貓眼電影TOP100實例
- python支持多線程的爬蟲實例
- Python 微信爬蟲完整實例【單線程與多線程】
- python面向?qū)ο蠖嗑€程爬蟲爬取搜狐頁面的實例代碼
- python爬蟲爬取快手視頻多線程下載功能
- Python3多線程爬蟲實例講解代碼
- php與python實現(xiàn)的線程池多線程爬蟲功能示例
- python 多線程爬取壁紙網(wǎng)站的示例
相關(guān)文章
關(guān)于pip安裝opencv-python遇到的問題
這篇文章主要介紹了關(guān)于pip安裝opencv-python遇到的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

