从文件中读取图片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. varnish启动报错

    错误1.Starting Varnish Cache: Error: Cannot open socket: :80: Address family not supported by protocol ...

  2. BZOJ4953 Wf2017Posterize(动态规划)

    设f[i][j]为前i种强度选了j种且其中第i种选时前i个的最小误差.转移枚举上个选啥前缀和优化即可. #include<iostream> #include<cstdio> ...

  3. [AT2172] [agc007_e] Shik and Travel

    题目链接 AtCoder:https://agc007.contest.atcoder.jp/tasks/agc007_e 洛谷:https://www.luogu.org/problemnew/sh ...

  4. 【HDU4336】Card Collector (动态规划,数学期望)

    [HDU4336]Card Collector (动态规划,数学期望) 题面 Vjudge 题解 设\(f[i]\)表示状态\(i\)到达目标状态的期望 \(f[i]=(\sum f[j]*p[j]+ ...

  5. tyvj1305 最大子序和 【单调队列优化dp】

    描述 输入一个长度为n的整数序列,从中找出一段不超过M的连续子序列,使得整个序列的和最大. 例如 1,-3,5,1,-2,3 当m=4时,S=5+1-2+3=7 当m=2或m=3时,S=5+1=6 输 ...

  6. 【bzoj1502】月下柠檬树

    Portal -->bzoj1502 Solution 额其实说实在这题我一开始卡在了..这个阴影长啥样上QwQ 首先因为是平行光线然后投影到了一个水平面上所以这个投影一定是..若干个圆再加上这 ...

  7. java类加载过程以及双亲委派机制

    前言:最近两个月公司实行了996上班制,加上了熬了两个通宵上线,状态很不好,头疼.牙疼,一直没有时间和精力写博客,也害怕在这样的状态下写出来的东西出错.为了不让自己荒废学习的劲头和习惯,今天周日,也打 ...

  8. tableau学习

    一.维度 度量 1. 连接到新数据源时,Tableau 会将该数据源中的每个字段分配给“数据”窗格的“维度”区域或“度量”区域,具体情况视字段包含的数据类型而定. 例如: 2. tableau中的字段 ...

  9. 洛谷P1396 营救

    题目描述 “咚咚咚……”“查水表!”原来是查水表来了,现在哪里找这么热心上门的查表员啊!小明感动的热泪盈眶,开起了门…… 妈妈下班回家,街坊邻居说小明被一群陌生人强行押上了警车!妈妈丰富的经验告诉她小 ...

  10. openssl生成https证书、转换证书格式的各种相关操作

    第一步:生成 private key.csr等文件 我们可能需要输入以下信息(交互式): --- Country Name (2 letter code) [AU]:US State or Provi ...