Python多线程下载文件的方法

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

相关文章

python脚本设置超时机制系统时间的方法

python脚本设置超时机制系统时间的方法

本文为大家介绍了python脚本设置系统时间的方法,一共有两种,其一是调用socket直接发送udp包到国家授时中心,其二是调用ntplib包。我在本地电脑ping 国家授时中心地址cn...

python tkinter控件布局项目实例

python tkinter控件布局项目实例

这篇文章主要介绍了python tkinter控件布局项目实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码部分: from...

Python实现公历(阳历)转农历(阴历)的方法示例

Python实现公历(阳历)转农历(阴历)的方法示例

本文实例讲述了Python实现公历(阳历)转农历(阴历)的方法。分享给大家供大家参考,具体如下: 两个要点: 1、公历转农历用了查表法(第126行) 2、节气用了天文法?(第176行)...

python字典排序实例详解

本文实例分析了python字典排序的方法。分享给大家供大家参考。具体如下: 1、 准备知识: 在python里,字典dictionary是内置的数据类型,是个无序的存储结构,每一元素是k...

python中requests和https使用简单示例

requests 是一个非常小巧全面的库,应用它可以很容易写出与服务器进行交互的程序,今天遇到了一个问题,与服务器交互时,url都是https开头的,都进行了ssl加密处理,这样一来,就...