python多线程下载大文件_Python threading多线程断点下载文件的方法
這是玩蛇網一篇關于Python多線程下載文件方法的代碼實例。文中應用到的python模塊和方法有httplib、Python urllib2、Python threading多線程模塊、python queue、sleep,這些方法或是模塊的具體實現流程可以參考本站的相關文章介紹。這是作者用了一小時左右寫出來的python抓取文件的代碼,喜歡的朋友可以拿去改進下。例如斷點續傳文件、多線程隊列下載文件,這樣的功能也是很受歡迎的,只是代碼不太好寫,需要一定的知識面和思路。
代碼中沒有太多的注釋,感覺大家知道這些python方法的話應該都明白我的思路。
(以上多線程演示圖片僅供參考!)
Python多線程下載文件的方法參考如下代碼段:
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;
#www.iplaypy.com
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()
感覺這個Python多線程下載文件的方法的方法還能再精簡一點,如果有哪位python大牛可以指教一二非常感謝。
玩蛇網文章,轉載請注明出處和文章網址:https://www.iplaypy.com/code/c2698.html
相關文章 Recommend
總結
以上是生活随笔為你收集整理的python多线程下载大文件_Python threading多线程断点下载文件的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP 获取格式化的日期和时间
- 下一篇: NPR技术(2)—Hatching 素描