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实现微信每天给女朋友说晚安 代码: # -*- co...

PyQt Qt Designer工具的布局管理详解

PyQt Qt Designer工具的布局管理详解

前言 这节课很重要。。界面整洁美观与否就看布局了。。这里讲布局方法,至于设计的天赋与最终界面的美感那就看造化了。。 本文主要讲述Qt Designer工具实现界面控件布局管理,就是排列组...

解决PyCharm import torch包失败的问题

Anaconda3-5.1.0-MacOSX-x86_64.pkg 下载安装后,附带安装了pytorch包。 需要将环境调整到新的python3.6目录下。 1、在Project Int...

关于Flask项目无法使用公网IP访问的解决方式

关于Flask项目无法使用公网IP访问的解决方式

最近在折腾Python Web,在测试的时候发现,本机可以正常访问,但外网无法通过公网IP访问页面。经过各种搜索,有大致三种解决方案。 一、修改/添加安全组端口 这是第一种方案,也是能解...

Python2.7 实现引入自己写的类方法

系统环境:win10 开发环境:JetBrains PyCharm 2017.1.5 x64 Python版本:2.7 假如我们有一个class叫DBUtil,它在A.py里(最好一...