Python实现批量下载文件


Posted in Python onMay 17, 2015

Python实现批量下载文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from gevent import monkey
monkey.patch_all()
from gevent.pool import Pool
import requests
import sys
import os

def download(url):
 chrome = 'Mozilla/5.0 (X11; Linux i86_64) AppleWebKit/537.36 ' + 
 '(KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'
 headers = {'User-Agent': chrome}
 filename = url.split('/')[-1].strip()
 r = requests.get(url.strip(), headers=headers, stream=True)
 with open(filename, 'wb') as f:
 for chunk in r.iter_content(chunk_size=1024):
 if chunk:
f.write(chunk)
f.flush()
 print filename,"is ok"

def removeLine(key, filename):
 os.system('sed -i /%s/d %s' % (key, filename))

if __name__ =="__main__":
 if len(sys.argv) == 2:
 filename = sys.argv[1]
 f = open(filename,"r")
 p = Pool(4)
 for line in f.readlines():
 if line:
 p.spawn(download, line.strip())
 key = line.split('/')[-1].strip()
 removeLine(key, filename)
f.close()
p.join()
else:
 print 'Usage: python %s urls.txt' % sys.argv[0]

其他网友的方法:

from os.path import basename
from urlparse import urlsplit
def url2name(url):
  return basename(urlsplit(url)[2])

def download(url, localFileName = None):
  localName = url2name(url)
  req = urllib2.Request(url)
  r = urllib2.urlopen(req)
  if r.info().has_key('Content-Disposition'):
    # If the response has Content-Disposition, we take file name from it
    localName = r.info()['Content-Disposition'].split('filename=')[1]
    if localName[0] == '"' or localName[0] == "'":
      localName = localName[1:-1]
  elif r.url != url:
    # if we were redirected, the real file name we take from the final URL
    localName = url2name(r.url)
  if localFileName:
    # we can force to save the file as specified name
    localName = localFileName
  f = open(localName, 'wb')
  f.write(r.read())
  f.close()

download(r'你要下载的python文件的url地址')

以上便是本文给大家分享的全部内容了,小伙伴们可以测试下哪种方法效率更高呢。

Python 相关文章推荐
跨平台python异步回调机制实现和使用方法
Nov 26 Python
python让图片按照exif信息里的创建时间进行排序的方法
Mar 16 Python
Python中的Numeric包和Numarray包使用教程
Apr 13 Python
Python时间模块datetime、time、calendar的使用方法
Jan 13 Python
Python 2.x如何设置命令执行的超时时间实例
Oct 19 Python
Python设计模式之适配器模式原理与用法详解
Jan 15 Python
Python标准库shutil模块使用方法解析
Mar 10 Python
Python获取对象属性的几种方式小结
Mar 12 Python
使用python客户端访问impala的操作方式
Mar 28 Python
详解Python直接赋值,深拷贝和浅拷贝
Jul 09 Python
Pygame框架实现飞机大战
Aug 07 Python
python使用列表的最佳方案
Aug 12 Python
python抓取最新博客内容并生成Rss
May 17 #Python
Python实现遍历数据库并获取key的值
May 17 #Python
Python对列表排序的方法实例分析
May 16 #Python
python中base64加密解密方法实例分析
May 16 #Python
python中threading超线程用法实例分析
May 16 #Python
python实现合并两个数组的方法
May 16 #Python
python简单实现基数排序算法
May 16 #Python
You might like
使用php方法curl抓取AJAX异步内容思路分析及代码分享
2014/08/25 PHP
浅谈PHP中JSON数据操作
2015/07/01 PHP
微信公众号支付之坑:调用支付jsapi缺少参数 timeStamp等错误解决方法
2016/01/12 PHP
php使用pear_smtp发送邮件
2016/04/15 PHP
PHP实现通过二维数组键值获取一维键名操作示例
2019/10/11 PHP
Web层改进II-用xmlhttp 无声息提交复杂表单
2007/01/22 Javascript
js整数字符串转换为金额类型数据(示例代码)
2013/12/26 Javascript
jquery制作弹窗提示窗口代码分享
2014/03/02 Javascript
js判断url是否有效的两种方法
2014/03/04 Javascript
javascript 处理null及null值示例
2014/06/09 Javascript
JavaScript indexOf方法入门实例(计算指定字符在字符串中首次出现的位置)
2014/10/17 Javascript
javascript图片切换综合实例(循环切换、顺序切换)
2016/01/13 Javascript
js根据手机客户端浏览器类型,判断跳转官网/手机网站多个实例代码
2016/04/30 Javascript
微信小程序封装http访问网络库实例代码
2017/05/24 Javascript
微信小程序的日期选择器的实例详解
2017/09/29 Javascript
JS实现电脑虚拟键盘的操作
2020/06/24 Javascript
[05:17]DOTA2睡衣妹卖萌求签名 CJ第二天全明星影像
2013/07/28 DOTA
Python Web框架Pylons中使用MongoDB的例子
2013/12/03 Python
基于DataFrame改变列类型的方法
2018/07/25 Python
对dataframe数据之间求补集的实例详解
2019/01/30 Python
django 单表操作实例详解
2019/07/30 Python
Python中的Cookie模块如何使用
2020/06/04 Python
Python 爬虫批量爬取网页图片保存到本地的实现代码
2020/12/24 Python
python绘图模块之利用turtle画图
2021/02/12 Python
浅谈CSS3鼠标移入图片动态提示效果(transform)
2017/11/06 HTML / CSS
英国优质鞋类专家:Robinson’s Shoes
2017/12/08 全球购物
机械电子工程专业自荐书
2014/06/10 职场文书
大学竞选班干部演讲稿
2014/08/21 职场文书
中华魂放飞梦想演讲稿
2014/08/26 职场文书
四风对照检查剖析材料
2014/10/07 职场文书
个人诉讼委托书范本
2014/10/17 职场文书
商务宴请邀请函范文
2015/02/02 职场文书
应届生简历自我评价
2015/03/11 职场文书
同学聚会通知书
2015/04/20 职场文书
用人单位聘用意向书
2015/05/11 职场文书
Python+pyaudio实现音频控制示例详解
2022/07/23 Python