从文件中读取图片url和名称,将url中的文件下载下来。文件中每一行包含一个url和文件名,用制表符隔开。

1、使用requests请求url并下载文件

def download(img_url, img_name):
with closing(requests.get(img_url, stream=True)) as r:
with open(os.path.join(out_dir, img_name), 'wb') as f:
for data in r.iter_content(1024):
f.write(data)

2、从文件中读取url,考虑文件较大,使用生成器的方式读取。

def get_imgurl_generate():
with open('./example.txt', 'r') as f:
for line in f:
line = line.strip()
yield imgs

3、使用多线程进行下载

lock = threading.Lock()
def loop(imgs):
while True:
try:
with lock:
img_url, img_name = next(imgs)
except StopIteration:
break
download_pic(img_url, img_name) img_gen = imgurl_generate() for i in range(0, thread_num):
t = threading.Thread(target=loop, args=(img_gen,))
t.start()

完整代码,加入异常处理

 # -*- coding: utf-8 -*-
import os
from contextlib import closing
import threading
import requests
import time headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
} #输出文件夹
out_dir = './output'
#线程数
thread_num = 20
#http请求超时设置
timeout = 5 if not os.path.exists(out_dir):
os.mkdir(out_dir) def download(img_url, img_name):
if os.path.isfile(os.path.join(out_dir, img_name)):
return
with closing(requests.get(img_url, stream=True, headers=headers, timeout=timeout)) as r:
rc = r.status_code
if 299 < rc or rc < 200:
print 'returnCode%s\t%s' % (rc, img_url)
return
content_length = int(r.headers.get('content-length', ''))
if content_length == 0:
print 'size0\t%s' % img_url
return
try:
with open(os.path.join(out_dir, img_name), 'wb') as f:
for data in r.iter_content(1024):
f.write(data)
except:
print 'savefail\t%s' % img_url def get_imgurl_generate():
with open('./final.scp', 'r') as f:
index = 0
for line in f:
index += 1
if index % 500 == 0:
print 'execute %s line at %s' % (index, time.time())
if not line:
print ur'line %s is empty "\t"' % index
continue
line = line.strip()
try:
imgs = line.split('\t')
if len(imgs) != 2:
print ur'line %s splite error' % index
continue
if not imgs[0] or not imgs[1]:
print ur'line %s img is empty' % index
continue
yield imgs
except:
print ur'line %s can not split by "\t"' % index lock = threading.Lock()
def loop(imgs):
print 'thread %s is running...' % threading.current_thread().name while True:
try:
with lock:
img_url, img_name = next(imgs)
except StopIteration:
break
try:
download(img_url, img_name)
except:
print 'exceptfail\t%s' % img_url
print 'thread %s is end...' % threading.current_thread().name img_gen = get_imgurl_generate() for i in range(0, thread_num):
t = threading.Thread(target=loop, name='LoopThread %s' % i, args=(img_gen,))
t.start()

python多线程下载文件的更多相关文章

  1. Python之FTP多线程下载文件之分块多线程文件合并

    Python之FTP多线程下载文件之分块多线程文件合并 欢迎大家阅读Python之FTP多线程下载系列之二:Python之FTP多线程下载文件之分块多线程文件合并,本系列的第一篇:Python之FTP ...

  2. Python之FTP多线程下载文件之多线程分块下载文件

    Python之FTP多线程下载文件之多线程分块下载文件 Python中的ftplib模块用于对FTP的相关操作,常见的如下载,上传等.使用python从FTP下载较大的文件时,往往比较耗时,如何提高从 ...

  3. python爬虫下载文件

    python爬虫下载文件 下载东西和访问网页差不多,这里以下载我以前做的一个安卓小游戏为例 地址为:http://hjwachhy.site/game/only_v1.1.1.apk 首先下载到内存 ...

  4. 多线程下载文件,ftp文件服务器

    1: 多线程下载文件 package com.li.multiplyThread; import org.apache.commons.lang3.exception.ExceptionUtils; ...

  5. 教你如何在 Android 使用多线程下载文件

    # 教你如何在 Android 使用多线程下载文件 前言 在 Android 日常开发中,我们会经常遇到下载文件需求,这里我们也可以用系统自带的 api DownloadManager 来解决这个问题 ...

  6. java 多线程下载文件 以及URLConnection和HttpURLConnection的区别

    使用 HttpURLConnection 实现多线程下载文件 注意GET大写//http public class MultiThreadDownload { public static void m ...

  7. java 多线程下载文件并实时计算下载百分比(断点续传)

    多线程下载文件 多线程同时下载文件即:在同一时间内通过多个线程对同一个请求地址发起多个请求,将需要下载的数据分割成多个部分,同时下载,每个线程只负责下载其中的一部分,最后将每一个线程下载的部分组装起来 ...

  8. java 网络编程基础 InetAddress类;URLDecoder和URLEncoder;URL和URLConnection;多线程下载文件示例

    什么是IPV4,什么是IPV6: IPv4使用32个二进制位在网络上创建单个唯一地址.IPv4地址由四个数字表示,用点分隔.每个数字都是十进制(以10为基底)表示的八位二进制(以2为基底)数字,例如: ...

  9. python多线程下载ts文件

    # -*- coding: utf-8 -*- """ Created on Wed Aug 22 15:56:19 2018 @author: Administrato ...

随机推荐

  1. C++解析-外传篇(1):异常处理深度解析

    0.目录 1.异常的最终处理 2.结束函数terminate() 3.小结 1.异常的最终处理 问题: 如果在main函数中抛出异常会发生什么? 如果异常不处理,最后会传到哪里? 下面的代码的输出什么 ...

  2. 【树链剖分换根】P3979 遥远的国度

    Description zcwwzdjn在追杀十分sb的zhx,而zhx逃入了一个遥远的国度.当zcwwzdjn准备进入遥远的国度继续追杀时,守护神RapiD阻拦了zcwwzdjn的去路,他需要zcw ...

  3. Overlaying GPS Coordinates for Camera Crosshairs

    Hey Guys! I am working on a project to allow us to implement GPS coordinates for the location of the ...

  4. pdf 下载整理

    pdf下载整理: using System; using System.Collections.Generic; using System.Linq; using System.Web; using ...

  5. HashCode与Equals回顾

    HashSet和HashMap一直都是JDK中最常用的两个类,HashSet要求不能存储相同的对象,HashMap要求不能存储相同的键. 那么Java运行时环境是如何判断HashSet中相同对象.Ha ...

  6. epoll的一些细节和注意事项

    epoll_event结构 struct epoll_event { uint32_t events; /* Epoll events */ epoll_data_t data; /* User da ...

  7. helm 安装prometheus operator 并监控ingress

    1.helm安装 curl https://raw.githubusercontent.com/helm/helm/master/scripts/get > get_helm.shchmod 7 ...

  8. 运行python时提示:ImportError: No module named plyvel ,ImportError No module named irc 解决过程:

    (当前python版本:2.7) 1.在git下载electrum-server: cd / git clone https://github.com/spesmilo/electrum-server ...

  9. LINUX安全加固操作

    1.禁止Ctrl-Alt-Delete组合键重启系统 vi /etc/inittab #ca::ctrlaltdel:/sbin/shutdown -t3 -r now 如果还存在下面的文件,则需要注 ...

  10. [洛谷P1709] [USACO5.5]隐藏口令Hidden Password

    洛谷题目链接:[USACO5.5]隐藏口令Hidden Password 题目描述 有时候程序员有很奇怪的方法来隐藏他们的口令.Binny会选择一个字符串S(由N个小写字母组成,5<=N< ...