Python多线程下载文件的方法

yipeiwu_com6年前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;
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程序设计有所帮助。

相关文章

深入了解Django中间件及其方法

深入了解Django中间件及其方法

前言 我们可以给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面等等。我们通过给几个特定视图函数加装饰器实现了这个需求,但是以后添加的视图函数可能也需要加上装饰器...

OpenCV 模板匹配

OpenCV 模板匹配

最近小编实现一个微信小程序「跳一跳」的自动化。 主要涉及到了OpenCV的模板匹配和边缘检测技术,以及Android开发调试工具ADB。 如果放在一起说,感觉内容有些多。 所以,分三期来...

举例讲解Python的lambda语句声明匿名函数的用法

所谓匿名函数,即是不需要定义函数,像表达式一样使用,不需要函数名(很多时候名字让我很困扰),一些简单的函数简单化, 举个例子 我需要两个整数相加的函数,通常是这么定义的 def ad...

python傅里叶变换FFT绘制频谱图

本文实例为大家分享了python傅里叶变换FFT绘制频谱图的具体代码,供大家参考,具体内容如下 频谱图的横轴表示的是 频率, 纵轴表示的是振幅 #coding=gbk...

Python re模块介绍

Python中转义字符 正则表达式使用反斜杠” \ “来代表特殊形式或用作转义字符,这里跟Python的语法冲突,因此,Python用” \\\\ “表示正则表达式中的” \ “,因为正...