360ITO技术社区
  • 首页
  • 文章
  • 快讯
  • 讨论
  • 问答
  • 小贴士
  • 代码块
  • 开源
  • 老论坛
登录 | 注册

360ITO技术社区  > 代码块

订阅代码

python 多线程下载文件

taotao879 发布于 8年前 ( comment 0条评论  查看:7180  收藏:0 )
import httplib
import urllib2
import time
from threading import Thread
from Queue import Queue
from time import sleep

proxy = 'your proxy';
opener = urllib2.build_opener( urllib2.ProxyHandler({'http':proxy}) )
urllib2.install_opener( opener )

ids = {};
for i in range(1,110):
	try:
		listUrl = "http://www.someweb.net/sort/list_8_%d.shtml" % (i);
		print listUrl;
		page = urllib2.urlopen(listUrl).read();
		speUrl = "http://www.someweb.net/soft/";
		speUrlLen = len(speUrl);
		idx = page.find(speUrl,0);
		while idx!=-1:
			dotIdx = page.find(".",idx + speUrlLen);
			if dotIdx != -1:
				id = page[idx + speUrlLen:dotIdx];
				ids[id] = 1;
			idx = page.find("http://www.someweb.net/soft/",idx + speUrlLen);
	except:
		pass;


q = Queue()
NUM = 5
failedId = [];

def do_somthing_using(id):
	try:
		url = "http://www.someweb.net/download.php?softid=%s&type=dx" % (id);
		h2 = httplib.HTTPConnection("your proxy", "you port");
		h2.request("HEAD", url);
		resp = h2.getresponse();
		header = resp.getheaders();
		location = header[3][1];		
		sContent = urllib2.urlopen(location).read();
		savePath = "C:\\someweb\\%s.rar" % (id);
		file=open(savePath,'wb');
		file.write(sContent);
		file.close();	
		print savePath + " saved";
	except:
		pass;

def working():
    while True:
        arguments = q.get()
        do_somthing_using(arguments)
        sleep(1)
        q.task_done()

for i in range(NUM):
    t = Thread(target=working)
    t.setDaemon(True)
    t.start()
for id in ids:
    q.put(id)

q.join()
0 有用 0 无用

共有0个评论 我要评论»

按时间排 按有用数排 按支持数排

网友回复/评论仅代表其个人看法,并不表明本社区同意其观点或证实其描述。

请尽量让自己的回复能够对别人有帮助

1.不欢迎无意义的回复/评论和类似“顶”、“沙发”之类没有营养的文字
如果只是想简单的表个态,请点 有用无用支持反对 等按钮
2.发言之前请再仔细看一遍文章,或许是您遗漏、误解了,理性讨论、切莫乱喷
3.严禁发布违法、违规的信息,请勿到处招贴广告、发布软文;
4.如果您发现自己的回复/评论不见了,请参考以上3条
5.不停制造违规、垃圾信息的,账户将被禁止

热门标签

  • JavaScript 27
  • android 4
  • delphi 3
  • SQLite 2
  • Python 2
  • Flash 2
  • 应用 1
  • 安装 1
  • 分辨率 1
  • css 1
  • PX 1
  • DIP 1
  • C/C++ 1
  • 文件操作 1
  • 图标资源 1

相关文章

周热点

月热点

Copyright ©2011-2012 360ITO技术社区 All Rights Reserved. | 关于 | 联系我们 | 杭州精创信息技术有限公司 浙ICP备09019653号-26|
▲