多线程下载图片 求助

Win_Man 2016-02-09 12:03:40
最近写爬虫需要下载大量的图片,我把需要下载的图片的url保存在url_list列表中,,因为单线程下载太慢,所以我想用多线程来下载,但是遇到的问题是,多线程中一部分线程结束之后,就没有动静了,程序并没有结束,是死锁了吗
我用了代理,每个线程使用的不同的代理,代理ip是我从代理网站上抓下来的
附上代码
线程函数:

def downloadImg(url_list,path,start,end,ip_obj):
print('thread %s is running...' % threading.current_thread().name)
ss = requests.session()
proxies = {ip_obj.type:"http://%s:%s" % (ip_obj.ip,ip_obj.port)}
thread_name = threading.current_thread().name
img_count = 0
for img_url in url_list[start:end]:
#time.sleep(1)
print "%s正在下载%d/%d张图" % (thread_name,img_count,end - start)
img_content = ss.get(img_url,proxies = proxies)
name = img_url.split(".")
with open(os.path.join(path,thread_name + "_"+str(img_count) +"."+name[-1]),'wb') as f:
f.write(img_content.content)
img_count = img_count + 1
time.sleep(5)
print('thread %s ended.' % threading.current_thread().name)

创建线程的代码:

thread_count = 0
thread = []
interval = len(url_list) / 30
start = 0
end = interval
while start < len(url_list):
t = threading.Thread(target=downloadImg,args=(url_list,path,start,end,ip_list[thread_count]),name="Thread" + str(thread_count))
thread.append(t)
start = end
end = end + interval
thread_count = thread_count + 1
for t in thread:
t.start()
for t in thread:
t.join()


...全文
212 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
屎克螂 2016-07-11
  • 打赏
  • 举报
回复
看着并没有什么问题 ss.get() 加个超时 线程设置一下setDaemon(True)
  • 打赏
  • 举报
回复
同问~同学你解决了吗?
Win_Man 2016-02-10
  • 打赏
  • 举报
回复
没有人吗

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧