1.读取txt文件中的图片链接放入队列中
2.多线程获取队列中的图片信息爬取图片
import requests
import threading
import queue
count = 0
class getImg(threading.Thread):
def __init__(self, queue): # 进程间通过队列通信,所以每个进程需要用到同一个队列初始化
threading.Thread.__init__(self)
self.queue = queue
# self.setDaemon(True) #守护线程
self.start() # 启动线程
# 使用队列实现进程间通信
def run(self):
global count
while (True):
imgurl = self.queue.get()
# print self.getName()
r = requests.get(imgurl[1])
with open(f'f:1/{count}.jpg', 'ab+') as f:
f.write(r.content)
count += 1
if self.queue.empty():
break
self.queue.task_done() # 当使用者线程调用 task_done() 以表示检索了该项目、并完成了所有的工作时,那么未完成的任务的总数就会减少。
def main():
threads = []
q = queue.Queue()
c = 0
with open('f:1.txt') as f:
for i in f:
q.put((c,i))
c +=1
# 多线程爬去图片
for i in range(50):
thread = getImg(q)
threads.append(thread)
for thread in threads:
thread.join()
if __name__ == '__main__':
main()
本文介绍了一种利用Python的多线程技术实现的图片爬虫程序,该程序能够从txt文件读取图片链接,使用队列进行线程间通信,高效地爬取并保存图片。
4982

被折叠的 条评论
为什么被折叠?



